malloc,分配矩阵

时间:2013-12-30 13:22:17

标签: c pointers

我以这种方式分配字符串向量:

    int number =0;
    char** matrix = (char**)malloc(10);
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);
    number++; //MAX 10

好的,我希望当没有字符串时,向量有一个空指针,所以我可以使用calloc:

    int number =0;
    char** matrix = (char**)calloc(10,1);
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);
    number++; //MAX 10

但是,如果我不想使用calloc,并使用malloc代替,将所有指针值inizial为null,为什么我在linux上获得SIGABRT信号?

    nt number =0;
    char** matrix = (char**)malloc(10);
    for (i=0;i<10;i++)
        matrix[i] = NULL;
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);    //ERROR: SIGABRT
    number++; //MAX 10

我认为在for cicle中我覆盖了一些关于分配的内存的特殊信息,有人可以解释一下它发生了什么吗?


谢谢anishsane,你是对的,但有时候我不尊重​​规则。太糟糕了......无论如何,sizeof(char)返回1,所以在这个例子中写10 * sizeof(char)和10只相同。 为什么在calloc函数中首先传递char的大小然后传递chars的数量?我在这里读到:http://www.cplusplus.com/reference/cstdlib/calloc/我应该首先传递字符数,然后传递sizeof

1 个答案:

答案 0 :(得分:9)

char** matrix = (char**)malloc(10);

应该是

char** matrix = (char**)malloc(10*sizeof(char*));

此外,

char** matrix = (char**)calloc(10,1);

应该是

char** matrix = (char**)calloc(sizeof(char*),10);