C语言打印字符串并替换字符为下划线功能缺失什么要素?
问题排查与修复方案
你代码里的核心问题和修复点如下:
- 野指针非法访问:声明的
char *current_status仅为未初始化的字符指针,没有指向任何合法可读写的内存空间,直接读取、写入操作都属于未定义行为,是你无法正常打印、程序运行异常的核心原因。可选择两种方案修复:- 定长数组声明:将
char *current_status;修改为char current_status[21];,匹配你预设的单词最长20字符的规格,额外预留1位存储字符串结束符 - 动态内存分配:在获取
word_length后加一行current_status = (char *)malloc(sizeof(char) * (word_length + 1));,程序使用完该变量后记得调用free(current_status)释放内存避免泄漏
- 定长数组声明:将
- 字符串缺少结束标志:C语言字符串以
\0作为结束标识,你给current_status的前word_length位赋值为_后,需要补充current_status[word_length] = '\0',否则用%s格式符打印时会持续读取后续内存直到碰到随机的\0,输出乱码内容 - 无效的前置打印操作:你在给
current_status赋值前就执行了printf("%s", current_status);,此时就算指针已经分配内存,存储的也是随机脏数据,这行代码直接删除即可 - 随机数逻辑缺陷:
rand()函数调用前需要先设置随机种子,否则每次运行程序都会拿到同一个固定的随机词。建议在main函数开头添加srand((unsigned int)time(NULL));,同时引入<time.h>头文件。另外你注释标注的selects a random number from 0 to 15不准确,rand()%15的取值范围是0~14,刚好匹配你15个元素的数组下标,逻辑没问题,仅注释需要修正。
修复后参考代码
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(void) { srand((unsigned int)time(NULL)); printf("Welcome to the Computer Science Themed Hangman Game!\n The words the you will be asked to guess in this game will be related to computer science.\n"); char words[15][20] = {"motherboard", "keyboard", "bytes", "programmer", "array", "processor", "loop", "algorithm", "intelligence", "boolean", "compute", "debug", "output", "function", "memory"}; int i, mistakes = 0; int random_word_index = rand() % 15; // 生成0~14的随机数,匹配数组下标 int word_length = strlen(words[random_word_index]); printf("%d\n", word_length); char *selected_word = words[random_word_index]; char word[20]; strcpy(word, selected_word); printf("选中的单词:%s\n", word); char current_status[21]; for (i=0; i<word_length; ++i){ current_status[i] = '_'; } current_status[word_length] = '\0'; printf("当前状态:%s\n", current_status); // 后续逻辑可继续补充 return 0; }
内容的提问来源于stack exchange,提问作者AleeSarion
相关产品推荐
相关产品推荐

