|
5鱼币
想实现的功能为输入英文句子,每个单词间用空格隔开,然后分别打印单词
编译后只能打印出来第一个单词,请问这是什么情况
- #include <stdio.h>
- int main()
- {
- char str[1024] = { 0 };
- char *sp = &str[0];
- int i, j;
- int count = 0, para = 0, max = 0;
- int get;
- printf("请输入一个英文句子:");
- while((get = getchar()) != '\n') //存储数据,获取长度和句子数量
- {
- *sp++ = get;
- count++;
- if(get == ' ' )
- {
- para++;
- if(count > max)
- {
- max = count;
- }
- count = 0;
- }
- }
- para++;
- char result[para][max]; //初始化可变长数组
- for(i = 0; i < para; i++)
- {
- for(j = 0; j < max; j++)
- {
- result[i][j] = 0;
- }
- }
- sp = &str[0]; //转移数据到result中
- for(i = 0; i < para; i++)
- {
- for(j = 0; j < max; j++)
- {
- if(*sp == 0 || *sp == ' ')
- {
- continue;
- }
- result[i][j] = *sp++;
- }
- }
- printf("分割结果已存入到result[%d][%d]中\n", para, max);
- for(i = 0; i < para; i++)
- {
- printf("%s\n", result[i]);
- }
- return 0;
- }
复制代码
问题出在对可变长数组的初始化上。在C语言中,可变长数组只能在运行时初始化,而不能在编译时初始化。因此,对于 char result[para][max] 这样的可变长数组,不能使用循环来进行初始化。
解决这个问题的方法是使用动态内存分配函数 malloc 来为 result 分配内存。下面是修改后的代码:
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- char str[1024] = { 0 };
- char *sp = &str[0];
- int i, j;
- int count = 0, para = 0, max = 0;
- int get;
- printf("请输入一个英文句子:");
- while((get = getchar()) != '\n') //存储数据,获取长度和句子数量
- {
- *sp++ = get;
- count++;
- if(get == ' ')
- {
- para++;
- if(count > max)
- {
- max = count;
- }
- count = 0;
- }
- }
- para++;
- char [color=Red]result = (char [/color])malloc(para * sizeof(char *)); //动态分配内存
- for(i = 0; i < para; i++)
- {
- result[ i] = (char *)malloc(max * sizeof(char));
- }
- sp = &str[0]; //转移数据到result中
- for(i = 0; i < para; i++)
- {
- for(j = 0; j < max; j++)
- {
- if(*sp == 0 || *sp == ' ')
- {
- continue;
- }
- result[ i][j] = *sp++;
- }
- }
- printf("分割结果已存入到result[%d][%d]中\n", para, max);
- for(i = 0; i < para; i++)
- {
- printf("%s\n", result[ i]);
- }
- //释放动态分配的内存
- for(i = 0; i < para; i++)
- {
- free(result[ i]);
- }
- free(result);
- return 0;
- }
复制代码
这样就能正确打印出输入的每个单词了。同时,为了避免内存泄漏,我们还在程序结束前释放了动态分配的内存。
|
-
最佳答案
查看完整内容
问题出在对可变长数组的初始化上。在C语言中,可变长数组只能在运行时初始化,而不能在编译时初始化。因此,对于 char result[max] 这样的可变长数组,不能使用循环来进行初始化。
解决这个问题的方法是使用动态内存分配函数 malloc 来为 result 分配内存。下面是修改后的代码:
这样就能正确打印出输入的每个单词了。同时,为了避免内存泄漏,我们还在程序结束前释放了动态分配的内存。
|