C struct initialization and pointer -
#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 program output 100? problem malloc? have no idea initialize struct.
how can desired output 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 statically allocated h1 again creating memory on heap , writing it.
so address passed function overwritten malloc() return address of malloc() memory on heap , not address object h1 stored.
Comments
Post a Comment