为什么我的函数错误地返回了2D数组的一部分?

时间:2019-10-21 20:48:22

标签: c

我正在编写一个程序,该程序需要读取地图文件并将数据保存为2D int数组。数据格式为:

6,2,4,5,3,9,1,7,7,
5,1,9,7,2,8,6,3,4,
8,3,7,6,1,4,2,9,5,
1,4,3,8,6,5,7,2,9,
9,5,8,2,4,7,3,6,1,
7,6,2,3,9,1,4,5,8,
3,7,1,9,5,6,8,4,2,
4,9,6,1,8,2,5,7,3,
2,8,5,4,7,3,9,1,6

我能够读取所有数据并将其正确存储在我的主要方法中,但是我想稍微清理一下代码,因此我尝试编写一个函数来打开文件,读取数据并创建一个静态数组,然后返回一个指向它的指针。问题是,当我尝试打印返回的数组时,它将在第一行中打印每行的第一个索引,然后在每隔一行中打印一串零。我尝试了几种取消引用单个索引的方法,并且一旦在readMap()函数之外引用数组,似乎数组发生了变化,但是我不知道为什么会发生这种情况。到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 20
typedef int MAP_ARRAY[9][9];

MAP_ARRAY * readMap(const char *fileName);

int main (int argc, char *argv[]) {

    MAP_ARRAY *map;
    map = readMap(argv[1]);
    for(int i = 0; i<9; i++){
      for(int j = 0; j<9; j++){
        printf("%d ", *map[i][j]);
      }
      printf("\n");
    }
    exit(EXIT_SUCCESS);

}

MAP_ARRAY* readMap(const char *fileName){
    FILE *mapFile;
    char *line = NULL;
    size_t buffSize = BUFFER_SIZE;
    size_t numChars;
    static MAP_ARRAY returnMap;
    mapFile = fopen(fileName,"r");

    if(mapFile == NULL){
      printf("Failed to open file.");
        exit(EXIT_FAILURE);
    }
    // Allocate space for line buffer
    line = (char *)malloc(buffSize * sizeof(char));
    int currLine = 0;
    while((numChars = getline(&line, &buffSize, mapFile)) != -1 && currLine < 9){
      char* token = strtok(line, ",");
      int input;
      int currIndex = 0;
      while(token != NULL && currIndex < 9){
        input = atoi(token);
        returnMap[currLine][currIndex] = input;
        token = strtok(NULL, ",");
        currIndex++;
      }
      currLine++;
    }
    for(int i = 0; i<9; i++){
      for(int j = 0; j<9; j++){
        printf("%d ", returnMap[i][j]);
      }
      printf("\n");
    }
    printf("\n");
    fclose(mapFile);
    return &returnMap;
}

我得到的输出是

6 2 4 5 3 9 1 7 7
5 1 9 7 2 8 6 3 4
8 3 7 6 1 4 2 9 5
1 4 3 8 6 5 7 2 9
9 5 8 2 4 7 3 6 1
7 6 2 3 9 1 4 5 8
3 7 1 9 5 6 8 4 2
4 9 6 1 8 2 5 7 3
2 8 5 4 7 3 9 1 6

6 5 8 1 9 7 3 4 2
0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

1 个答案:

答案 0 :(得分:6)

问题在这里:

    printf("%d ", *map[i][j]);

它错误地解释了多个取消引用。当i = 1时,它将跳过整个数据结构来计算map[i](这不是您想要的)。您需要以下内容:

    printf("%d ", (*map)[i][j]);

要详细说明不正确的代码的作用:让我们以示例i = 0, j = 3为例。我使用*pointerpointer[0]相同的想法。然后:

  • map[i] = map[0] = *map = map指向的事物。这就是整个二维数组。
  • map[i][j] = map[0][3] = *map中索引为3的元素=数组索引为3的行
  • *map[i][j] = *map[0][3] = map[0][3][0] =索引为3的行中的第一个元素

另一个示例:i = 4, j = 8。然后:

  • map[i] = map[4] =无限3-D数组中索引为4的元素,其元素为2-D数组int[9][9]。这超出范围,因此它会打印一个随机的内存位置。