如何将内存分配给空字符串数组
how to assign memory to a empy string array
我得到一个空字符串数组,大小为 1(自动为 1,我真的不知道为什么)
我想将大小为 10 的空字符串数组分配给该空字符串数组,但我不知道该怎么做?
到目前为止,这是我的代码
char empty_string_array[] = "";
printf("Enter some strings: eg. asdfjklo...: ");
scanf("%s", &empty_string_array[0]);
int len_of_string = strlen(empty_string_array);
printf("%d\n", len_of_string);
输入:输入一些字符串...:a
输出:字符串的当前长度:1
重启
输入:输入一些字符串....:ab
*检测到堆栈粉碎 * 已中止(核心已转储)
我想这意味着,没有为多个字符串分配内存,除了已经存在的那个
我知道我可以使用:char empty_string_array[11] = "";对于 10 个字符串和 \0 ,但这并不是最好的解决方案
既然你必须使用malloc()
那么
char *empty_string_array = (char *)malloc(sizeof(char) * 10 + 1);
//casting from (void *) is not really necessary, though
printf("Enter some strings: eg. asdfjklo...: ");
scanf("10%s", empty_string_array);
int len_of_string = strlen(empty_string_array);
*(empty_string_array+len_of_string) = '[=10=]';
//or: empty_string_array[len_of_string] = '[=10=]'; your pick
printf("%d\n", len_of_string);
我得到一个空字符串数组,大小为 1(自动为 1,我真的不知道为什么)
我想将大小为 10 的空字符串数组分配给该空字符串数组,但我不知道该怎么做?
到目前为止,这是我的代码
char empty_string_array[] = "";
printf("Enter some strings: eg. asdfjklo...: ");
scanf("%s", &empty_string_array[0]);
int len_of_string = strlen(empty_string_array);
printf("%d\n", len_of_string);
输入:输入一些字符串...:a 输出:字符串的当前长度:1
重启 输入:输入一些字符串....:ab *检测到堆栈粉碎 * 已中止(核心已转储)
我想这意味着,没有为多个字符串分配内存,除了已经存在的那个
我知道我可以使用:char empty_string_array[11] = "";对于 10 个字符串和 \0 ,但这并不是最好的解决方案
既然你必须使用malloc()
那么
char *empty_string_array = (char *)malloc(sizeof(char) * 10 + 1);
//casting from (void *) is not really necessary, though
printf("Enter some strings: eg. asdfjklo...: ");
scanf("10%s", empty_string_array);
int len_of_string = strlen(empty_string_array);
*(empty_string_array+len_of_string) = '[=10=]';
//or: empty_string_array[len_of_string] = '[=10=]'; your pick
printf("%d\n", len_of_string);