歧义用C二维数组声明 [英] Ambiguity in 2d array declaration in C
本文介绍了歧义用C二维数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面的格式定义的数组,但显然程序只在CASE B.正常工作
I have defined array in the following formats, but apparently the program works fine only in CASE B.
方案A:
int **M1;
M1 = (int **)malloc(m * sizeof(int *));
for (int i=0; i<m; i++){
M1[i] = (int *)malloc(d * sizeof(int));
}
方案B:
int (*M1)[m] = malloc(sizeof(int[m][d]));
我得到的情况下,A的分割错误可能是什么原因?
I am getting a segmentation error in CASE A. What could be the reason?
推荐答案
以下code没有错误或警告编译在 GCC
编译器,
The following code compiles without error or warning in gcc
compiler,
int **M1,i;
M1 = (int **)malloc(5 * sizeof(int *));
for (i=0;i<5;i++){
M1[i] = (int *)malloc(2 * sizeof(int));
}
M1[0][0]=111;
M1[0][1]=222;
printf("\n%d %d",M1[0][0],M1[0][1]);
给出 111 222
作为输出。
问题可能是一些别的地方在你的code。
The problem might be some where else in your code.
这篇关于歧义用C二维数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文