Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
malloc,分配一个矩阵_C_Pointers - Fatal编程技术网

malloc,分配一个矩阵

malloc,分配一个矩阵,c,pointers,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

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

    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,将所有指针值初始化为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
nt编号=0;
字符**矩阵=(字符**)malloc(10);
对于(i=0;i
应该是

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

应该是

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

sizeof(char**)!=sizeof(char)
指针是4字节的内存。
(char**)malloc(10)
尝试分配2.5
char*
位置!@Rikayanbandyopadhay,它是32位体系结构上的4个字节。根据经验,除非您编写了过度特定于平台的代码,否则不应该对指针的大小进行假设。这就是
sizeof
的目的。@StoryTeller,是的。我的错误!然后您应该处理这个问题失败案例:
if(matrix==NULL){perror(“malloc”);exit(exit_failure);}
不需要在C中强制转换
mallic/calloc/realloc
。一条注释,用于初始化的
calloc
假设所有字节都设置为0的指针都是空指针。@alk:是的,没错。我只想在这里指出致命错误。但是是的,你的注释绝对正确。
char** matrix = (char**)calloc(10,1);
char** matrix = (char**)calloc(sizeof(char*),10);