You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言随机字符串生成时为何额外多出2个字符?

C语言随机字符串生成长度异常的解决方法

你定义了长度为9的字符数组password,计划存储8个有效字符+1个空终止符,但代码只循环给索引0到7的位置赋值,没有手动设置索引8的位置为'\0'。C语言中字符串必须以'\0'结尾,strlen()和printf("%s")都是通过寻找'\0'来判断字符串结束位置的,未初始化的数组元素是内存里的随机垃圾值,因此会越界读取直到遇到某个'\0',导致长度显示异常。

解决方案

在生成完8个字符的循环结束后,手动添加空终止符:

password[8] = '\0';

修改后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main() {
    int n = 5; // 可根据需求修改循环次数
    char password[9];
    srand(time(NULL)); // 初始化随机数种子,避免重复序列

    for(int cnt = 0; cnt < n; cnt++){
        for(int i = 0; i < 8; i++){
            if (i < 3){
                password[i] = rand() % 26 + 'A'; // 用字符常量替代ASCII码更易读
            } else if (i < 6){
                password[i] = rand() % 26 + 'a';
            } else {
                password[i] = rand() % 10 + '0';
            }
        }
        password[8] = '\0'; // 关键:添加字符串终止符
        printf("%s\n", password);
        printf("%d\n", strlen(password));
    }
    return 0;
}

额外提示

  • 用字符常量(如'A'、'a'、'0')替代直接写ASCII码值,代码可读性更强。
  • 必须调用srand(time(NULL))初始化随机数种子,否则每次运行程序生成的字符串序列会完全相同。

内容的提问来源于stack exchange,提问作者herion05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 07:34:58