I am new to C, and I'm trying to populate a 2D array by breaking a text file of instructions into sub-strings and storing them into it. This loop is to populate said Array, within the while loop, it prints perfectly fine and seems to store it correctly. After the while loop, the 2D array is now empty and I do not understand why.
I should not have to allocate memory from the Heap as this is all within the same function correct? If I'm wrong, please let me know what I should be doing instead, thank you.
My goal is to have an instruction like
mul 2 4
be stored into
instructionArr[0][0] = mul
instructionArr[0][1] = 2
instructionArr[0][2] = 4
Is this the correct way to even go about this?
char instruction[256];
char* instructionArr[100][5];
int line = 0;
while(fgets(instruction, 256, fp) != NULL) {
printf("%s", instruction);
char* tokenized = strtok(instruction, " ");
int count = 0;
while (tokenized != NULL) {
printf("tokenized: line: %d, position: %d is: %s\n", line, count, tokenized);
instructionArr[line][count] = tokenized;
//Prints string correctly
printf("tokenizedArr[%d][%d] = %s\n", line, count, instructionArr[line][count]);
tokenized = strtok(NULL, " ");
count ++;
}
line ++;
}
//Print the first element of instructionArr, [0][0], should be a string, but is nothing.
printf("tokenizedArr[%d][%d] = %s\n", 0, 0, instructionArr[0][0]);
strtok modifies the string it operates on. See https://wiki.sei.cmu.edu/confluence/display/c/STR06-C.+Do+not+assume+that+strtok%28%29+leaves+the+parse+string+unchanged
Also you should probably use strcpy() instead of "instructionArr[line][count] = tokenized;"
EDIT: strncpy() is safer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.