【发布时间】:2011-02-03 01:22:08
【问题描述】:
我还是 C、malloc 和所有爵士乐的新手,所以我决定写这篇文章来学习更多技能。这个想法是,我正在从文件中读取一堆整数并将它们放入矩阵(二维数组)中。文件的开头说明有多少行和列,因此它会读取这些数字并使用 malloc 设置二维数组。
int read_matrix(FILE *mat, int ***Z, int *x, int *y)
{
int i = 0;
int x_temp = 0;
int y_temp = 0;
if (fscanf(mat, "%d %d", &(*x), &(*y)) == EOF){
printf("File is not big enough to contain a matrix\n");
return -1;
}
printf("About to malloc %d\n", *x);
*Z = (int**) malloc(*x * sizeof(int*));
while (i < *x) {
printf("mallocing %d\n", i);
*Z[i] = (int*) malloc(*y * sizeof(int));
printf("malloced\n");
++i;
}
printf("Malloc complete\n");
/*Other unimportant code*/
}
输出如下:
About to malloc 3
mallocing 0
malloced
mallocing 1
Segmentation fault
所以它在 Z 中除了一个 int** 之外没有分配任何东西。我认为?
我对 C 很陌生,所以我不确定我是否犯了一些小错误,或者我是否真的把整个事情都搞错了。有什么想法吗?谢谢!
【问题讨论】:
-
&(*x)与x相同。 -
啊啊啊是啊,忽略 &(*x) 因为我是个白痴哈哈