用于访问2D数组中元素的精确语法 - 通过指针?

时间:2016-09-27 19:16:06

标签: c arrays pointers multidimensional-array malloc

我是一名从事家庭作业的CS学生,我需要有关C语法问题的帮助。我的教授昨天在课堂上说,“int **指针是指向2D int数组的指针。”这引起了我的注意。

事实证明,我们必须编写一个C程序,它从文件中读取一个int矩阵,然后对该矩阵进行操作。例如,“matrix1.txt”可能如下所示:

 1   2   3   4   5
 6   7   8   9  10
11  12  13  14  15

...用于5x3矩阵。我从另一个文件中获取矩阵的维度,这是我已经解决的问题。但重点是我必须使用变量动态分配矩阵数组。

这是我的问题:使用指向malloc()的一个Y-by-X数组的int **指针很容易......但是访问它的语法是什么?这是我的代码:

#include<stdio.h>
#include<stdlib.h>

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

    char *myFile = argv[1];
    FILE *targetFile;
    targetFile = fopen(myFile, "r");

    if (targetFile == NULL)
        return -1;
    else {
        // Successfully opened "matrix1.txt" file
        int x, y;                                           // dimensions of the array, learned elsewhere...
        int i, j;
        char* data = NULL;

        int** matrix = (int**)malloc((x*y)*sizeof(int));    // allocate memory for an Y-by-X array

        for(i=0; i<y; i++){
            for(j=0; j<x; j++){
                fscanf(targetFile, "%c ", &data);
                matrix[i][j] = atoi(data);                  // program seg faults here
            }
        }
    }
    fclose(targetFile);
    return 1;
}

问题是“matrix [i] [j] = atoi(数据);”线;我要么使用错误的语法,要么我没有初始化数组。我无法分辨哪个 - 一旦我在GDB调试器中点击这一行,程序段就会立即出错。

我确定这是一个C 101类型的问题...但我发布这个是因为我一直在阅读关于2D数组和指针的很多不同帖子,但我似乎无法找到一个例子符合我的确切情况。任何人都可以帮我解决这个问题吗?

 Thanks,
   -ROA

1 个答案:

答案 0 :(得分:1)

中使用的语法
matrix[i][j] = atoi(data);

不正确。它是用于分配错误内存的逻辑。

为2D阵列分配内存的一种方法是:

// Allocate memory for y number of int*s.
int** matrix = malloc(y*sizeof(int*));
for(i=0; i<y; i++)
{
   // Allocate memory for x number of ints.
   matrix[i] = malloc(x*sizeof(int));
   for(j=0; j<x; j++)
   {
      // Assign to the ints
      matrix[i][j] = <some value>;
   }
}

要阅读数据,请使用

int data;

fscanf(targetFile, "%d", &data);

然后,上面的内部循环可以更新为:

   for(j=0; j<x; j++)
   {
      // Assign to the ints
      fscanf(targetFile, "%d", &data);
      matrix[i][j] = data;
   }

确保添加代码以释放动态分配的内存。

// Free the memory allocated for the ints
for(i=0; i<y; i++)
{
   free(matrix[i])
}

// Free the memory allocated for the int*s
free(matrix);
相关问题