Reputation: 676
#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?
Upvotes: 3
Views: 97
Reputation: 7
Initially pointer t was pointing to address of t1, later in modify function, pointer t was pointing to the memory returned by the malloc.
t->id = 100; was initializing the memory returned by malloc, hence you are not seeing this getting reflected in the main when
printf("%d\n", t1.id);
is executed.
Upvotes: 0
Reputation: 19874
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.
Upvotes: 3