char **arr;
arr = (char **)calloc(1,sizeof(char*));
for(i = 0; i< 16; i++)
if(arr[i] = (char *)calloc(1, 2*sizeof(char)) == NULL)
perror("Memory cannot be allocated to arr[i]", %d);
Run Code Online (Sandbox Code Playgroud)
当我尝试将内存分配给arr [i]时,上面的代码在for循环中抛出一个错误.这个分配有什么问题.本质上,我想存储16个长度为2的字符串.我也尝试过使用指针数组(char*arr [16]).我尝试使用malloc()和calloc()查找双指针初始化的资源,但找不到很多.如果你能指出一些链接,那将非常感激.谢谢.
你需要为16个指针分配足够的内存,而不只是一个.
arr = (char **)calloc(16, sizeof(char*));
Run Code Online (Sandbox Code Playgroud)
你的代码会发生什么,arr
只有一个指针有足够的内存,所以arr[0] = <something>
是正确的,但arr[1]
更高的是触及不属于程序的内存.
另外,分配字符串指针的方式是错误的.您正在分配0或1值,具体取决于结果是否calloc
为NULL
.你需要在那里添加括号:
if ((arr[i] = (char *)calloc(1, 2*sizeof(char))) == NULL)
perror("Memory cannot be allocated to arr[%d]", i);
Run Code Online (Sandbox Code Playgroud)
甚至更好:
for(i = 0; i < 16; i++) {
arr[i] = (char *)calloc(1, 2*sizeof(char));
if (arr[i] == NULL) {
perror("Memory cannot be allocated to arr[%d]", i);
}
}
Run Code Online (Sandbox Code Playgroud)
使用时calloc
,通常使用第一个参数传递数组中元素的数量,第二个参数传递元素的大小。因此,要分配一个包含16个指针的数组,通常会使用calloc(16, <pointer size>)
,而不是calloc(1, 16 * <pointer size>)
,尽管两者都做同样的事情。在您的代码中,您显然完全忘记了16,而只分配了1个指针。
不要转换'calloc'的结果。
sizeof(<type>)
在计算内存分配函数的大小时避免使用。更喜欢使用sizeof *<pointer>
。
如果要存储长度为2的小节,则需要至少3个字符长的缓冲区(对于零终止符,需要额外的字符)。
内存分配失败通常不会设置errno
,因此perror
此处不适合使用此功能。
尤尔分配arr[i]
的if
条件缺少括号。操作关联不正确。它不会按原样编译。
char **arr;
arr = calloc(16, sizeof *arr);
for(i = 0; i < 16; i++)
if((arr[i] = calloc(3, sizeof *arr[i]) == NULL)
fprintf(stderr, "Memory cannot be allocated");
Run Code Online (Sandbox Code Playgroud)
最后,未命名的“魔术常数”(16和3)在大多数情况下不是一个好主意。