简体   繁体   English

我在 C 中的 2D 数组在 while 循环中填充后为空,但在循环中它显示正确填充

[英]My 2D Array in C is empty after populating it in a while loop, but within the loop it appears populated correctly

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.我是 C 的新手,我试图通过将指令的文本文件分解为子字符串并将它们存储到其中来填充 2D 数组。 This loop is to populate said Array, within the while loop, it prints perfectly fine and seems to store it correctly.这个循环用于填充所述数组,在 while 循环中,它打印得非常好并且似乎正确地存储了它。 After the while loop, the 2D array is now empty and I do not understand why.在 while 循环之后,二维数组现在是空的,我不明白为什么。

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多 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. strtok 修改它操作的字符串。 See https://wiki.sei.cmu.edu/confluence/display/c/STR06-C.+Do+not+assume+that+strtok%28%29+leaves+the+parse+string+unchangedhttps://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;"此外,您可能应该使用 strcpy() 而不是“instructionArr[line][count] = tokenized;”

EDIT: strncpy() is safer编辑:strncpy() 更安全

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM