【发布时间】:2020-05-07 13:33:49
【问题描述】:
我分配了一个二维字符数组,在读取没有空格的字符串时,代码运行良好。当我用空格阅读它们时,我遇到了一个错误。如何读取所有 N 个字符串,每个字符串都在一行中,每个字符串都包含空格。
示例输入:
Enter total number of Strings : 3
Enter all the 3 Strings :
John Doe
Jane Doe
Trad Braversy
我的代码:
// Code to enter the total number of Strings :
int N;
printf("\n\tEnter the total number of Strings : ");
scanf("%d", &N);
// Code for allocating initial memory to them :
char** strings = (char**)malloc(N * sizeof(char*));
for (int i = 0; i < N; ++i) {
strings[i] = (char*)malloc(1024 * sizeof(char));
}
// Code for entering all the N strings :
printf("\n\tEnter all the %d Strings :\n", N);
for (int i = 0; i < N; ++i) {
gets(strings[i]);
}
// Code to reallocate the memory according to the entered length :
for (int i = 0; i < N; ++i) {
strings[i] = (char*)realloc(strings[i], strlen(strings[i]) + 1);
}
【问题讨论】:
-
您提供的代码有效吗?有什么问题吗?
-
从不使用
gets。我想我会做一些考古学,以确定该建议何时成为常识,如果最终答案是在 1981 年之后的任何时候,我会感到惊讶。但要找到很久以前的数据可能会很困难。 -
@KamilCuk 如果我输入的字符串之间没有空格,那就可以了。如果我给 N = 3,并开始扫描带空格的字符串,它会扫描 2 并且剩余的代码正在执行,其他字符串不会被扫描。
-
@xing 不,我在循环上方添加了一个提示,说:“输入所有 N 个字符串:”,即使在那之后代码也一样。
-
@WilliamPursell 不幸的是,“Let us C”一书在印度仍然很受欢迎。我看了一眼那本书,真是太可怕了。
标签: c string malloc c-strings gets