I would like to ask question regarding pointers. I dont know what to do here, I have a method in the main that is calling a method outside the main, and I need to use pointers.Basically this is the rough draft of it: Thanks!
char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};
struct data{ char *bookname; int booknumber;};
struct data *list[3];
my_method(char *x, int y, int *z)
{
//creating a new struct
list[(*z)++] = (struct data*) malloc( sizeof(struct data) );
//assigning arguments
list[(*z)++]->bookname = x;
list[(*z)++]->booknumber = y;
(*z)++;
}
int main()
{
int nextValue = 0;
my_method(book[nextValue], book[nextValue], &nextValue);
int i;
for(i = 0; i < 3; i++)
{
function(book[i], number[i]);
printf("name: %c number: %d", list[i]->bookname, list[i]->booknumber);
}
}
It looks like you are passing the wrong arguments to your method. Try changing the following line:
my_method(book[nextValue], number[nextValue], &nextValue);
In addition, in your method you seem to be incrementing z four times, which I doubt is the behavior you want. You should only increment it once at the end, like the following:
//creating a new struct
list[*z] = (struct data*) malloc( sizeof(struct data) );
//assigning arguments
list[*z]->bookname = x;
list[*z]->booknumber = y;
(*z)++;
Try the following code. Simply removed unnecessary static void.
//declaration of method outside the main
void my_method(............,int *nextValue)
{
//................................//
//..............................//
//then increment the pointer
(*nextValue)++;
}//my_method
int main()
{
int nextValue = 0;
//Removed static void
my_method(............, &nextValue);
//........................................//
}//main
Related
I have difficulty applying the pass by reference and pass by value separation in structs.How can I swap the elements of the fixed size struct array as below.
struct try{
int num;
char name[10];
};
int main(){
struct try book[3];
void swapper(/********/);// <-what should be the argument of this function
}
void swapper(/********/){//swap second and third element of struct array
/*how the swap may be done?
temp=book[2];
book[2]=book[3];
temp=book[3];*/
}
There are a lot of ways to do what you're asking. One approach:
#include <stdio.h>
struct try {
int num;
char name[10];
};
void
swapper(struct try *a, int b, int c)
{
struct try tmp = a[b];
a[b] = a[c];
a[c] = tmp;
}
void
display(const struct try *t, size_t count)
{
while( count-- ){
printf("%d: %s\n", t->num, t->name);
t += 1;
}
}
int
main(void) {
struct try book[] = {
{ 1, "foo"},
{ 2, "bar"},
{ 3, "baz"}
};
display(book, sizeof book / sizeof *book);
swapper(book, 1, 2);
display(book, sizeof book / sizeof *book);
return 0;
}
Well I am wanting to change the way my structures are written, currently I use array and I need to limit its use, but I wanted a way to create a dynamic array that is the size of the reading done, without always having to edit the array value.
Current Code:
struct sr_flag {
int value_flag;
};
struct er_time {
int value_time;
};
struct se_option {
struct sr_flag flag[50];
struct er_time time[50];
};
struct read_funcs
struct se_option *option;
void (*option_func) (void);
...
}
struct read_funcs func_;
struct read_funcs *func;
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
return func->option[i].flag[fg].value_flag = val;
}
void option_func(void) {
struct se_option fnc;
fnc.option = malloc(500 * sizeof(*(fnc.option)));
}
void read_fnc() {
func = &func_;
func->option = NULL;
func->option_func = option_func;
}
I look for a way to remove the array amount [50] instead each time the sr_flags function is executed the limit is raised
Example: sr_flags function executed 1x array would be [1] if executed 2x would be [2]
I also think about doing the same with the option_func function
I tried using the following more unsuccessfully
struct se_option {
struct sr_flag *flag;
struct er_time time[50];
};
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
func->option[i].flag = malloc(1 * sizeof(*(func->option[i].flag)));
return func->option[i].flag[fg].value_flag = val;
}
int main () {
for(int i < 0; i < 10; i++)
sr_flags(i, 1, 30);
return 0;
}
I'm not 100% certain on what it is you want but I think you just want to call realloc and increase the size by the amount you provide. And that's very easy to do, as for the values you want with the arrays I'm not sure so I just used a placeholder value.
#include <stdio.h>
#include <stdlib.h>
struct sr_flag {
int value_flag;
};
struct er_time {
int value_time;
};
struct se_option {
struct sr_flag* flag;
struct er_time* time;
};
void allocateflags(struct se_option* options, int size, int val){
options->flag = realloc(options->flag, size*sizeof(struct sr_flag));
struct sr_flag* flag = options->flag+size-1;
flag->value_flag = val;
}
void allocatetime(struct se_option* options,int size, int val){
options->time = realloc(options->time, size*sizeof(struct er_time));
struct er_time* time = options->time+size-1;
time->value_time = val;
}
void displayflagvalues(struct se_option* options,int size){
for(int index = 0; index < size ; ++index){
printf("flag: %i\n",options->flag[index].value_flag);
}
}
void displaytimevalues(struct se_option* options, int size){
for(int index = 0; index < size ; ++index){
printf("time: %i\n",options->time[index].value_time);
}
}
int main(){
struct se_option options = {0};
for(int index = 0; index < 10; ++index){
allocateflags(&options, index,index);
allocatetime(&options, index,index);
}
displayflagvalues(&options, 10);
displaytimevalues(&options,10);
return 0;
}
The code creates an se_option structure wheren sr_flag and er_time pointers are null. Then there's two functions one allocateflags and the other allocatetime, both of which call realloc with the size you provide. When you call realloc, all previous memory is copied over to the new array. Also free is called automatically by realloc.
This step
struct sr_flag* flag = options->flag+size-1;
flag->value_flag = val;
struct er_time* time = options->time+size-1;
time->value_time = val;
Is slightly redundant but it was just to show the newest array can hold the value. If you understand pointer arithmetic, all its doing is incrementing the pointer to the last position then subtracting 1 struct size and setting that value. Basically setting the value of the final array in the pointer.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do function pointers in C work?
Surfing on stackoverflow I found this example:
/* Validation functions start */
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
...
}
I was wondering, imagine getNextRandomValue had a parameter getNextRandomValue(int i), how would I include this and making the function accepting inputs?
Many thanks
Common practice is to pass a pointer to "data" together with the function. When function gets called, pass that "data" pointer into function and assume that the function itself knows what to do with that data. In fact the data is usually a pointer to a structure. So the code looks like this:
struct func1_data {
int a;
int b;
};
struct func2_data {
char x[10];
};
int function1(void *data) {
struct func1_data *my_data = (typeof(my_data)) data;
/* do something with my_data->a and my_data->b */
return result;
}
int function2(void *data) {
struct func2_data *my_data = (typeof(my_data)) data;
/* do something with my_data->x */
return result;
}
and assume we have
int caller(int (*callback), void *data) {
return callback(data);
}
Then you call all this like this:
struct func1_data data1 = { 5, 7 };
struct func2_data data2 = { "hello!" };
caller(function1, (void *) &data1);
caller(function2, (void *) &data2);
It's probably a good idea to get familiar with function-pointer syntax. You need to change the argument to int (*getNextValue)(int).
Then your code should be like this...
void populate_array(int *array, size_t arraySize, int (*getNextValue)(unsigned int))
{
unsigned int seedvalue = 100;
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue(seedvalue);
}
int getNextRandomValue(unsigned int seed)
{
srand(seed);
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
...
}
Lets say I have the following code (the array* function are what we use for resizable arrays and they operate on pointers-to-arrays that are null initialized):
typedef struct MyStruct
{
int i;
} MyStruct;
MyStruct* GetNewMyStruct(int i)
{
MyStruct* s = malloc(sizeof(MyStruct));
s->i = i;
return s;
}
int SomeFunction(int number, MyStruct *elem)
{
MyStruct **structs = NULL;
int i;
for (i = 0; i < number; i++)
arrayPush(&structs, GetNewMyStruct(i));
arrayPush(&structs, elem);
return arraySize(&structs);
}
I decide that SomeFunction is too large and I want refactor it. Currently where I work we use VisualAssist X, which has some refactoring capabilities, but when I use it on this it does not work correctly. If I attempt to use it to refactor out the loop, this is what I get:
void MyMethod( int number, MyStruct ** structs )
{
int i;
for (i = 0; i < number; i++)
arrayPush(&structs, GetNewMyStruct(i));
}
int SomeFunction(int number, MyStruct *elem)
{
MyStruct **structs = NULL;
MyMethod(number, structs);
arrrayPush(&structs, elem);
return arraySize(&structs);
}
This is not correct. MyMethod should take a MyStruct ***, not a MyStruct **. This is because the code I'm refactoring takes the address of structs. The result is that the refactored version will always return 1 (since only one object has been pushed into my array) rather than number+1. Are there other tools out there that do this type of refactoring correctly?
Eclipse CDT does this correctly (at least the current version Juno). Selecting the declaration of i and the loop and doing Refactor > Extract Function, and setting structs to be an output parameter, produces:
void MyMethod(int number, MyStruct*** structs) {
int i;
for (i = 0; i < number; i++)
arrayPush(&*structs, GetNewMyStruct(i));
}
int SomeFunction(int number, MyStruct *elem)
{
MyStruct **structs = NULL;
MyMethod(number, &structs);
arrayPush(&structs, elem);
return arraySize(&structs);
}
I declared an array of struct and initialized it at compile time.
Now, for unit testing purposes, I would like to initialize it from a function which I can call from main() and from my unit tests.
For some reason, probably involving a 16 hour coding marathons & exhaustion, I can't figure it out.
So assuming you have
struct foo {
int a;
int b;
};
struct foo foo_array[5] = {
{ 0, 0 }, { 1, 1 }, { 2, 2 }
};
int main() {
memcpy(foo_array, some_stuff, sizeof(foo_array)); // should work
...
OR you could:
int main() {
int i;
for ( i = 0; i < sizeof(foo_array)/sizeof(struct foo); i++ ) {
init(&foo_array[i]);
}
}
but without looking at your code it's hard to say what's causing the trouble... i am SURE it's probably something very trivial you are overlooking because you are tired and have been at it for 16 hours.
typedef struct {
int ia;
char * pc;
} St_t;
void stInit(St_t * pst) {
if (!pst)
return;
pst->ia = 1;
pst->pc = strdup("foo");
/* Assuming this function 'knows' the array has two elements,
we simply increment 'pst' to reference the next element. */
++ pst;
pst->ia = 2;
pst->pc = strdup("bar");
}
void foo(void) {
/* Declare 'st' and set it to zero(s)/NULL(s). */
St_t st[2] = {{0}, {0}};
/* Initialise 'st' during run-time from a function. */
stInit(st);
...
}
see this one:
struct Student
{
int rollNo;
float cgpa;
};
int main()
{
const int totalStudents=10;
Student studentsArray[totalStudents];
for(int currentIndex=0; currentIndex< totalStudents; currentIndex++)
{
printf("Enter Roll No for student # %d\n" , currentIndex+1);
scanf("%d\n", &studentsArray[currentIndex].rollNo);
printf("Enter CGPA for student # %d\n", currentIndex+1);
scanf("%d\n", &studentsArray[currentIndex].cgpa);
}
}