C语言程序无输出无输入直接终止问题排查求助
C语言程序问题排查:输入语句未执行直接终止+首字母提取逻辑错误
一、程序直接终止的核心原因
- 未定义
SIZE宏:main函数中char sentence[SIZE]的SIZE未定义,编译阶段会直接报错,导致程序无法正常启动,这是printf和gets未执行就终止的关键原因。需在代码开头添加#define SIZE 1024(或其他合适的数组长度)来解决。 gets函数已被废弃:gets属于不安全函数,存在缓冲区溢出风险,现代编译器会直接拒绝编译该函数,也是程序无法正常执行的原因之一。建议替换为fgets,并手动去除读取到的换行符:fgets(sentence, SIZE, stdin); sentence[strcspn(sentence, "\n")] = '\0'; // 移除末尾换行符
二、FirstLetters函数的逻辑错误
即便解决输入问题,原函数的首字母提取逻辑仍存在多处错误:
- 指针类型不匹配:
int *firstchar, *p = sent, *q;中firstchar应为char*类型,使用int*会导致类型错误与内存操作异常。 - 单词计数逻辑错误:原代码仅通过空格数量累加计数,无法处理开头空格、连续空格的情况,会导致单词数统计错误。正确计数方式应判断是否处于单词中:
int counter = 0; int in_word = 0; while (*p != '\0') { if (*p != ' ' && !in_word) { counter++; in_word = 1; } else if (*p == ' ') { in_word = 0; } p++; } - 首字母提取逻辑错误:原代码中
*q = *p + 1是将空格的ASCII值加1(得到!),并非下一个单词的首字母。正确逻辑应为遇到空格时,跳过所有连续空格,提取下一个非空格字符。 - 未分配字符串结束符空间:
malloc(counter)仅分配了单词首字母的空间,未预留\0的位置,会导致puts输出乱码,应改为malloc(counter + 1),并手动添加*q = '\0'。
三、修正后的完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 1024 // 定义输入数组大小 char *FirstLetters(char *sent) { char *p = sent; int counter = 0; int in_word = 0; // 统计有效单词数量 while (*p != '\0') { if (*p != ' ' && !in_word) { counter++; in_word = 1; } else if (*p == ' ') { in_word = 0; } p++; } // 分配内存(包含字符串结束符空间) char *firstchar = (char *)malloc(counter + 1); if (firstchar == NULL) { // 检查内存分配是否成功 printf("Memory allocation failed\n"); exit(1); } char *q = firstchar; p = sent; // 跳过开头的连续空格 while (*p == ' ') p++; if (*p != '\0') { *q++ = *p; } // 提取后续单词的首字母 while (*p != '\0') { if (*p == ' ') { while (*p == ' ') p++; // 跳过连续空格 if (*p != '\0') { *q++ = *p; } } p++; } *q = '\0'; // 添加字符串结束符 return firstchar; } int main() // main函数标准返回类型为int { char sentence[SIZE]; char *firstletter; printf("Enter a sentence: "); fgets(sentence, SIZE, stdin); sentence[strcspn(sentence, "\n")] = '\0'; // 移除换行符 firstletter = FirstLetters(sentence); printf("The result is: \n\n"); puts(firstletter); free(firstletter); // 释放动态分配的内存,避免内存泄漏 return 0; }
四、额外注意事项
main函数的标准返回类型是int,而非void,这是C语言标准要求,可避免编译警告。- 必须检查
malloc的返回值,防止内存分配失败导致程序崩溃。 - 使用完动态分配的内存后需调用
free,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

