2011-07-07 74 views
1

我尝试了一切,并从我的理解,这段代码是正确的,但它仍然给我的分段错误。帮帮我?Dynamic Multidimensional Arrays

#include <stdio.h> 
#include<malloc.h> 

void da(int ***array, int row, int col){ 
    int i; 
    *array=(int **)malloc(sizeof(int *)*row); 
    for (i=0; i<row; i++) 
     *array[i]=(int *)malloc(sizeof(int)*col); 
} 

main(){ 
    int **array; 
    int i,n,m; 
    printf("Input number of rows: "); 
    scanf("%d",&n); 
    printf("Input number of columns: "); 
    scanf("%d",&m); 
    da(&array,n,m); 
    for (i=0; i<n; i++) 
     free(array[i]); 
    free(array); 
} 
+0

它在哪里段错误?你到目前为止尝试解决这个问题? –

+0

请勿施放'malloc'的返回值。铸造充其量是多余的,并且(**和你的代码**一样)可能会隐藏错误; *即没有声明'malloc'的头文件,使得编译器假定返回类型是'int'而不是'void *'。* – pmg

回答

6

操作[]比运营商更*优先。 放上括号:(*array)[i]=(int *)malloc(sizeof(int)*col);

0

该代码似乎没问题。我的猜测是其中一个malloc失败(返回NULL),因为你没有检查响应。 NULL上的空闲显然失败。这可能是一个剩余的记忆问题。你使用的是哪些行和列的数字?

其他建议。此代码过于复杂。由于您创建的是常规矩阵,因此创建单维数组更简单,更高效。

void da(int **array, int row, int col){ 
    int i; 
    *array=(int *)malloc(sizeof(int)*row*col); 
    return; }