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 highly doubt this is what your teacher had in mind, but you can cheat using a series of legal type conversions.
Then your caller does the same:
This relies on a rule in C that says any pointer to an object can be implicitly converted to a void pointer, and vice-versa, without loss.
Note that formally this is undefined, but it is all but sure to work. While any object pointer value is required to be able to convert to a
void*and back without loss, there is nothing in the language that guarantees that asome_struct*can store asome_struct**without loss. But it has a very high likelihood of working just fine.Your teacher gave you no option but to write formally illegal code. I don’t see that you have any other option besides “cheating” like this.