我已经在这个代码上工作了几个小时,并且对为什么 printf 只打印垃圾感到困惑,我是堆栈溢出的新手,并且对 C 相当陌生,所以请原谅我这篇文章中的任何错误。我研究了指向数组结构的指针,但找不到任何有用的东西。
typedef struct my
{
int x;
int y;
} My;
My * main2(void);
void show(void)
{
My * m = main2();
printf("%u\n", m);
printf("%u\n", m);
printf("%d\n", m->x);
printf("%d\n", m->y);
m++;
printf("%u\n", m);
printf("%d\n", m->x);
printf("%d\n", m->y);
m++;
printf("%u\n", m);
printf("%d\n", m->x);
printf("%d\n", m->y);
}
My * main2(void)
{
My j[3];
j[0].x = 2;
j[0].y = 4;
j[1].x = 3;
j[1].y = 5;
j[2].x = 7;
j[2].y = 9;
printf("%u\n", j);
return j;
}
int main()
{
show();
return 0;
}
最佳答案
函数内定义的变量仅具有该函数的生命周期。一旦函数返回,变量本质上就不存在了。
现在,如果您返回指向此类变量的指针(或像您一样返回数组的第一个元素)并且该数据不再存在,那么您将得到 undefined behavior当您尝试使用指针时。
解决此类问题的一种方法是将数组(或者再次将指向其第一个元素的指针)作为参数传递给函数:
void main2(My *j)
{
j[0].x = 2;
// And so on...
}
要将数组传递给函数,请记住,当在需要指针的上下文中使用时,数组会衰减为指向其第一个元素的指针。
这意味着您可以像传递任何其他变量一样传递它:
My arr[3];
main2(arr); // equal to main2(&arr[0]);
<小时/>
另一方面,使用 printf
打印指针的格式是“%p”
。指针也需要转换为void *
:
printf("%p\n", (void *) j);
关于C 指针 - 作为数组的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139883/