Search code examples
carraysfgets

Value assigned in array changes, and I do not understand why


so I am pretty new to C programming, and am having a problem that I truly do not understand. I am reading lines from a file, and trying to store each line (as a string) in an array. I am then using strtok on that line to parse another value out of the line. For some reason, the value I put in the array changes after I use strtok. Code is below:

while(fgets(readLine, 100, inFile) != NULL) { 
    printf("j = %d\n", j);
    puts(readLine); 
    machineList[j] = readLine;
    puts(machineList[j]); //the value of machineList[j] at this point is equal
                          // to the current readLine 

    int i=0;

    day = strtok(readLine, " ,");

    puts(machineList[j]); //the value of machineList[j] at this point is no
                          //longer what it was at the previously noted point

    while(i<3) {
        day=strtok(NULL, " ,");
        i++;
    }
    dayList[j]=atoi(day);

    printf("Day is: %d\n\n", dayList[j] );  //these values come out as expected
    j++;

}

Can anyone explain why this is happening? I don't understand, since its not like I am reassigning machineList[j]=readLine. Thus, even if the value of readLine changes, it shouldn't change the value in machineList[j]. Again, I am new to C, so I realize my code semantics could be awful- anything is helpful. Thanks!


Solution

  • strtok modifies the original string by replacing the delimiters with null bytes.

    I assume machineList is an array of pointers to char, so this:

    machineList[j] = readLine;
    

    ...makes machineList[j] a pointer to readLine. Then this:

    day = strtok(readLine, " ,");
    

    ...modifies readLine, which also modifies machineList[j] since it points to it. You'll want to make a copy instead:

    // allocate machineList[j]
    strcpy(machineList[j], readLine);
    

    If you don't make a copy, when your while loop ends, machineList will basically be an array of dangling pointers.