1

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

4

1 に答える 1

3

これは未定義の動作です。そのポインターの背後にオブジェクトはありません。結果は何でもかまいません。未定義の動作は機能しているように見えることもあれば、非常に不可解な方法で失敗することもあります。

次のようにアプローチできます。

thing th;
thing* s = &th;
...now 's' points to a 'thing' -- specifically, 'th'.
于 2012-09-10T07:57:38.430 に答える