扫描到二维数组,然后将其传递给函数 - C
Scanning to 2d array and then passing it to function - C
如果我将函数分配为一维数组然后将其传递给函数,我的程序将出现分段错误。它是为二维数组构建的。问题是,我无法找到如何分配二维数组以及如何将其正确传递给函数的方法。希望一切都解释清楚。如果您知道出了什么问题,请尝试引导我以正确的方式解决它。非常感谢。这是代码:
int main()
{
int i, j, size;
scanf("%d", &size);
int *a;
//here i try to allocate it as 2d array
*a = (int *)malloc(size * sizeof(int));
for (i=0; i<size; i++)
{
a[i] = (int *)malloc(size * sizeof(int));
}
//here i scan value to 2d array
for (i = 0; i < size; i++)
for (j = 0; j < size; j++){
scanf("%d", &a[i][j]); }
//here i pass array and size of it into function
if (is_magic(a,size))
函数头看起来像:
int is_magic(int **a, int n)
这行不通:
*a = (int *)malloc(size * sizeof(int));
因为 a
的类型为 int *
,所以 *a
的类型为 int
,因此将指针分配给它没有意义。您还试图取消引用尚未初始化的指针,调用 undefined behavior.
您需要将 a
定义为 int **
:
int **a;
并在第一次分配时直接分配给它,使用 sizeof(int *)
作为元素大小:
a = malloc(size * sizeof(int *));
另请注意 you shouldn't cast the return value of malloc
。
扫描二维数组 ? 为此,您需要从 int**
类型获取 a
而不仅仅是 int*
类型。例如
int **a = malloc(NUM_OF_ROW * sizeof(int*)); /* allocate memory dynamically for n rows */
然后为每一行分配内存,例如
for (i=0; i<size; i++){
a[i] = malloc(NUM_OF_COLUMN * sizeof(int)); /* in each row how many column, allocate that much memory dynamically */
}
如果我将函数分配为一维数组然后将其传递给函数,我的程序将出现分段错误。它是为二维数组构建的。问题是,我无法找到如何分配二维数组以及如何将其正确传递给函数的方法。希望一切都解释清楚。如果您知道出了什么问题,请尝试引导我以正确的方式解决它。非常感谢。这是代码:
int main()
{
int i, j, size;
scanf("%d", &size);
int *a;
//here i try to allocate it as 2d array
*a = (int *)malloc(size * sizeof(int));
for (i=0; i<size; i++)
{
a[i] = (int *)malloc(size * sizeof(int));
}
//here i scan value to 2d array
for (i = 0; i < size; i++)
for (j = 0; j < size; j++){
scanf("%d", &a[i][j]); }
//here i pass array and size of it into function
if (is_magic(a,size))
函数头看起来像:
int is_magic(int **a, int n)
这行不通:
*a = (int *)malloc(size * sizeof(int));
因为 a
的类型为 int *
,所以 *a
的类型为 int
,因此将指针分配给它没有意义。您还试图取消引用尚未初始化的指针,调用 undefined behavior.
您需要将 a
定义为 int **
:
int **a;
并在第一次分配时直接分配给它,使用 sizeof(int *)
作为元素大小:
a = malloc(size * sizeof(int *));
另请注意 you shouldn't cast the return value of malloc
。
扫描二维数组 ? 为此,您需要从 int**
类型获取 a
而不仅仅是 int*
类型。例如
int **a = malloc(NUM_OF_ROW * sizeof(int*)); /* allocate memory dynamically for n rows */
然后为每一行分配内存,例如
for (i=0; i<size; i++){
a[i] = malloc(NUM_OF_COLUMN * sizeof(int)); /* in each row how many column, allocate that much memory dynamically */
}