user3002440
user3002440

Reputation: 13

Coding in C, Why are my array values changing?

I'm using GDB to go through my code and each time the while loop is entered, the values in NameList[] change. Like I set NameList[0] to chr2, but when I go back through the while loop in gdb, I say x/s NameList[0] and now it's set to the new value of chr2! How is this able to happen? I know I'm changing the pointer, but shouldn't the array be storing the old value of the pointer and not be allowed to update?

while (fgets(thisline, length, input) != NULL) {
    chr = strtok(Line, "    ");
    if(chr != NULL) {
        chr2 = strtok(chr, " ")
        int j = 0;
        while(NameList[j] != NULL) {
            j++;
        }
        NameList[j] = chr2;
    }
}

Upvotes: 1

Views: 136

Answers (1)

Charlie Burns
Charlie Burns

Reputation: 7056

Try changing

    NameList[j] = chr2;

to

    NameList[j] = strdup(chr2);

And see what happens. The issue is that you are just storing a pointer to the char array, and that char array is changing out from under you. The strdup function copies the whole array.

Upvotes: 1

Related Questions