# Thread: Allocating dynamic memory for structs

1. ## Allocating dynamic memory for structs

Hi, i have a small problem i can't seem to figure out, although i remember the problem from previous code uh somewhere and i know it should be possible somehow :]

Anyway, lets say i have a struct looking like this:

struct foo {
int x;
char bar[20];
};

And a function to put data into the struct looking like this:

void foobar (struct foo **barf, int elements) {
int i;
for(i=0; i<elements; i++) {
barf[i]->x = 1;
strcpy(barf[i]->bar, "FooBar");
}
}

And a main function looking like this:

int main(void) {
struct foo *bar;
const int elements = 4;
bar = malloc(elements*sizeof(struct foo));
/* Now we should have a 4 elements array of struct foo */
/* And writing data to the struct in this function should be no problems but, calling foobar() to write the data causes a segfault. */
foobar(&bar, elemenrs);
free(bar);
}

I'm sure the answer is simple, and managing this should be possible somehow

Cheers

2. ## corrected code

struct foo {
int x;
char bar[20];
};

void foobar (struct foo *barf, int elements) {
int i;
for(i=0; i<elements; i++) {
(&barf[i])->x = 1;
strcpy(barf[i]->bar, "FooBar") ;
}
}

int main(void) {
struct foo *bar;
const int elements = 4;
int i;
bar = (struct foo*)malloc(elements*sizeof(struct foo));
/* Now we should have a 4 elements array of struct foo */
/* And writing data to the struct in this function should be no problems but, calling foobar() to write the data causes a segfault. */

foobar(bar,elements);
free(bar);

}
=============Regards, Mangesh=======

3. ## one correction

Hello,

The code sent by me has a small correction in function foobar()

void foobar (struct foo *barf, int elements)
{
int i;
for(i=0; i<elements; i++) {
(&barf[i])->x = 1;
strcpy((&barf[i])->bar, "FooBar") ;
}
}

Thanx and regards,
Mangesh.

4. Ahhh thats it, thanks man

5. > (&barf[i])->x = 1;
> strcpy((&barf[i])->bar, "FooBar") ;
Which reduces to (when you remove unnecessary indirections)
barf[i].x = 1;
strcpy( barf[i].bar, "FooBar") ;