#include <stdio.h>
typedef struct hello{
int id;
}hello;
void modify(hello *t);
int main(int argc, char const *argv[])
{
hello t1;
modify(&t1);
printf("%d\n", t1.id);
return 0;
}
void modify(hello *t)
{
t = (hello*)malloc(sizeof(hello));
t->id = 100;
}
Why doesn't the program output 100? Is it a problem with malloc? I have no idea to initialize the struct.
How can I get desired output by editing modify only?
void modify(hello *t)
{
t = (hello*)malloc(sizeof(hello));
t->id = 100;
}
should be
void modify(hello *t)
{
t->id = 100;
}
Memory is already statically allocated to h1 again you are creating memory on heap and writing to it.
So the address passed to the function is overwritten by malloc()
The return address of malloc() is some memory on heap and not the address the object h1 is stored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With