简体   繁体   English

指向C中的结构混淆

[英]pointer to structure confusion in C

I've written some code that doesn't want to work, and after much thought I've decided that the cause of all my trouble is a loop that is trying to copy strings to an array, which is a component of a structure, pointed to by a pointer passed to the function. 我写了一些不想工作的代码,经过深思熟虑,我已经确定我所有麻烦的原因是一个循环,试图将字符串复制到一个数组,这是一个结构的组件,指向传递给函数的指针。 This isn't exactly my code, but whatever is making this not work is also making my code not work: 这不完全是我的代码,但无论如何使这不起作用也使我的代码不起作用:

typedef struct {
        int A[100];
        } thing;

this something vaguely like the structure I'm using. 这个东西模糊地像我正在使用的结构。

Then within the main function: 然后在主函数内:

thing *s;
int i;
for (i=0;i<5;i++) {
    s->A[i]=i;
}

So, this doesn't work. 所以,这不起作用。 Much to my dismay and confusion, however, this does: 然而,令我感到沮丧和困惑的是,这样做:

thing *s;
s->A[0]=0;
s->A[1]=1;
s->A[2]=2;
s->A[3]=3;
s->A[4]=4;

Concerning this, I am at a loss, and have spent much time indeed trying to find a solution for myself. 关于这一点,我很茫然,并且花了很多时间确实试图为自己找到解决方案。 I know I'm missing something here, I just hope it's not obvious 我知道我在这里遗漏了一些东西,我只是希望它不是很明显

That's undefined behavior; 这是未定义的行为; there is no object behind that pointer -- the result could be anything. 指针后面没有任何对象 - 结果可能是任何东西。 Undefined behavior can appear to work, or it can fail in very mysterious ways. 未定义的行为似乎可行,或者它可能以非常神秘的方式失败。

You could approach it like this: 你可以像这样接近它:

thing th;
thing* s = &th;
...now 's' points to a 'thing' -- specifically, 'th'.

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

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