我是一名 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(data);”线;我要么使用了错误的语法,要么我没有初始化数组。我不知道是哪个 - 一旦我在 GDB 调试器中点击这一行,程序就会立即出现段错误。
我确定这是一个 C 101 类的问题......但我发布这个是因为我已经阅读了很多关于二维数组和指针的不同帖子,但我似乎找不到一个例子适合我的确切情况。谁能帮我解决这个问题?
Thanks,
-ROA
最佳答案
中使用的语法
matrix[i][j] = atoi(data);
没有错。错误的是用于分配内存的逻辑。
为二维数组分配内存的一种方法是:
// 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);
关于c - 访问二维数组中元素的精确语法 - 通过指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732625/