【发布时间】:2014-12-29 15:30:40
【问题描述】:
就像标题已经说明的那样,我想将各种字符串复制到二维数组中。每个字符串都有不同的大小,因此我需要使用内存重新分配。下面的代码应该可以完成这项工作,但不知何故我无法让它工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char **str = NULL;
int str_num = 1;
// get string
char *str_new = "hey mate\0";
printf("%s\n",str_new);
// reallocation for str_new
str = realloc(str,str_num*sizeof(char));
str[str_num-1] = realloc(str,strlen(str_new));
// copy string to new space
strcpy(*str, str_new);
// displaying string
printf("%s\n",str[str_num-1]);
return EXIT_SUCCESS;
}
【问题讨论】:
-
两件事:编译器自动将字符串终止符
'\0'添加到所有字符串文字中,并且所有字符串文字都是只读的,因此指向它们的指针应该是const。