Hi
I'll go straight to it. I'm working on an assignment, where I suddenly ran into trouble. I have to allocate a struct from within another function, obviously using pointers. I've been staring at this problem for hours and tried in a million different ways to solve it.
This is some sample code (very simplified):
...
some_struct s;
printf("Before: %d\n", &s);
allocate(&s);
printf("After: %d\n", &s);
...
/* The allocation function */
int allocate(some_struct *arg) {
arg = malloc(sizeof(some_struct));
printf("In function: %d\n", &arg);
return 0;
}
This does give me the same address before and after the allocate-call:
Before: -1079752900
In function: -1079752928
After: -1079752900
I know it's probably because it makes a copy in the function, but I don't know how to actually work on the pointer I gave as argument. I tried defining some_struct *s instead of some_struct s, but no luck. I tried with:
int allocate(some_struct **arg)
which works just fine (the allocate-function needs to be changed as well), BUT according to the assignment I may NOT change the declaration, and it HAS to be *arg.. And it would be most correct if I just have to declare some_struct s.. Not some_struct *s. The purpose of the allocation function is to initialize a struct (a some_struct), which also includes allocating it.
One more thing I forgot to mention. The return 0 in the allocate function is reserved for some status messages and therefore I can't return the address using this.
I hope I make sense and some of you out there can help me :P
Thanks in advice.
And thanks guys for formatting my code.