【问题标题】:My 2D Array in C is empty after populating it in a while loop, but within the loop it appears populated correctly我在 C 中的 2D 数组在 while 循环中填充后为空,但在循环中它似乎正确填充
【发布时间】:2021-03-03 10:16:33
【问题描述】:

我是 C 新手,我试图通过将指令文本文件分解为子字符串并将它们存储到其中来填充二维数组。该循环用于填充所述数组,在 while 循环中,它打印得非常好,并且似乎可以正确存储它。在while循环之后,二维数组现在是空的,我不明白为什么。

我不应该从堆中分配内存,因为这都在同一个函数中,对吗?如果我错了,请告诉我应该怎么做,谢谢。

我的目标是有一个类似的指令

mul 2 4

存入

instructionArr[0][0] = mul 
instructionArr[0][1] = 2 
instructionArr[0][2] = 4

这是解决这个问题的正确方法吗?

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]);

【问题讨论】:

  • 提示:在您自己动手之前,请尝试在某处定义诸如 256 之类的常量,以便您可以始终如一地使用它们,例如 #define BUFFER_SIZE 256,然后使用它。
  • “instructionArr的第一个元素,[0][0],应该是一个字符串”用你自己的话说,为什么instructionArr 的类型是什么?那么instructionArr[0]的类型是什么?那么instructionArr[0][0]的类型是什么?
  • 这里有多个逻辑错误。看来您不明白char 类型是不是“字符串”,实际上代表的是单个字符。或者至少,如果你明白这一点,你就没有正确地解释它。
  • insturctionArr[0][0] 的第一个元素应该是一个字符串,因为这是我试图存储到其中的内容。 instructionArr 是一个char数组对吗?那是C中的字符串吗? instructionArr 是一个二维字符数组,哦...我想我看到了错误,我没有存储 100x5 字符串,我存储的是 100x5 字符,这就是这里的问题吗?
  • 啊我意识到我有一个错误,应该是 char* instructionArr[100][5];不是 char 指令Arr[100][5];但是,我的问题仍然存在

标签: arrays c memory multidimensional-array


【解决方案1】:

strtok 修改它所操作的字符串。 见https://wiki.sei.cmu.edu/confluence/display/c/STR06-C.+Do+not+assume+that+strtok%28%29+leaves+the+parse+string+unchanged

你也应该使用 strcpy() 而不是 "instructionArr[line][count] = tokenized;"

编辑:strncpy() 更安全

【讨论】:

  • 简单地更改为strcpy 不是一个好主意,因为左侧目前没有指向任何地方
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2013-11-03
  • 1970-01-01
  • 2015-04-30
相关资源
最近更新 更多