Malloc inside another function (ANSI C)
Posted
by Casper
on Stack Overflow
See other posts from Stack Overflow
or by Casper
Published on 2010-04-08T15:47:20Z
Indexed on
2010/04/08
16:03 UTC
Read the original article
Hit count: 349
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.
I hope I make sense and some of you out there can help me :P
Thanks in advice
© Stack Overflow or respective owner