Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 328
Zizheng Wu Avatar asked Feb 04 '26 19:02

Zizheng Wu


1 Answers

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.

like image 51
Gopi Avatar answered Feb 06 '26 11:02

Gopi