简体   繁体   English

C struct初始化和指针

[英]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 ? 为什么程序输出100 Is it a problem with malloc ? 这是malloc的问题吗? I have no idea to initialize the struct. 我不知道初始化结构。

How can I get desired output by editing modify only? 如何仅通过编辑modify获得所需的输出?

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. 内存已经静态分配给h1 ,你在堆上创建内存并写入内存。

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. 因此,传递给函数的地址被改写malloc()的返回地址malloc()是堆一些内存,而不是对象的地址h1被存储。

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指向t1的地址,稍后在修改函数中,指针t指向malloc返回的内存。

t->id = 100; t-> id = 100; was initializing the memory returned by malloc, hence you are not seeing this getting reflected in the main when 正在初始化malloc返回的内存,因此你没有看到这反映在主要的时候

printf("%d\\n", t1.id); printf(“%d \\ n”,t1.id);

is executed. 被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM