Assigning a value to a variable gets stored in the wrong spot?

Posted by scribbloid on Stack Overflow See other posts from Stack Overflow or by scribbloid
Published on 2010-04-30T01:00:40Z Indexed on 2010/04/30 1:07 UTC
Read the original article Hit count: 197

Filed under:
|
|

Hello,

I'm relatively new to C, and this is baffling me right now. It's part of a much larger program, but I've written this little program to depict the problem I'm having.

#include <stdio.h>

int main()
{
    signed int tcodes[3][1];

    tcodes[0][0] = 0;
    tcodes[0][1] = 1000;
    tcodes[1][0] = 1000;
    tcodes[1][1] = 0;
    tcodes[2][0] = 0;
    tcodes[2][1] = 1000;
    tcodes[3][0] = 1000;
    tcodes[3][1] = 0;

    int x, y, c;

    for(c = 0; c <= 3; c++)
    {
        printf("%d %d %d\r\n", c, tcodes[c][0], tcodes[c][1]);

        x = 20;
        y = 30;
    }

}

I'd expect this program to output:

0 0 1000
1 1000 0
2 0 1000
3 1000 0

But instead, I get:

0 0 1000
1 1000 0
2 0 20
3 20 30

It does this for any number assigned to x and y. For some reason x and y are overriding parts of the array in memory.

Can someone explain what's going on?

Thanks!

© Stack Overflow or respective owner

Related posts about beginner

Related posts about c