user1659462
user1659462

Reputation: 11

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

Upvotes: 1

Views: 122

Answers (1)

justin
justin

Reputation: 104698

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'.

Upvotes: 3

Related Questions