emge
emge

Reputation: 487

Setting array value in struct sets a different field in struct

I have a piece of code as follows, and when the line with comment (//error here) executes, it sets the status variable instead of the element in the array.

I moved the int status element above the array_name element in the struct definition and that seemed to have fixed it, I suspect that I am changing a pointer and am missing some parenthesis, but i am not sure why this was happening.

#define MAX_NUM 20
typedef struct FOO_T {
    bool abc;
    int id;
    int array_name[MAX_NUM];
    int counter;
    int status;
    SYSTEMTIME timestamp;

    struct FOO_T *next;
}

if (curr->array_name[code] == 0 )
{
    curr->counter++;
    curr->array_name[code] =  curr->counter; //error here
}

I also initialize the whole struct in a different function, part of that function is this:

thing->id = 0;
for (i = 0; i < MAX_NUM; i++) thing->array_name[i] = 0;
thing->counter = 0;
thing->status = 0;

Upvotes: 0

Views: 293

Answers (1)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

You should check that code is less than MAX_NUM.

In your particular case code is probably MAX_NUM + 1

Upvotes: 3

Related Questions