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.5char*
位置!@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);