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

C语言二维数组打印异常:生成20个个体种群时输出错误

问题分析与修正:C语言二维字符串数组输出乱码问题

问题背景

我想要创建一个包含20个个体的种群,每个个体的名称(或gens)从字符池中随机生成。以下是我的代码:

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

int main()
{
    srand(time(0));
    // dice KOPYA = int dice = rand() % 101;

    int pop = 20; //Population Number
    int genCount = 5; //Number of gens for 1 person in population

    char a[] = "a";
    char gens[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    char target[] = "NuriY";
    char population[pop][genCount];
    char nextPopulation[pop][genCount];

    for(int i=0;i<pop;i++)
    {
        for(int j=0;j<=genCount-1;j++)
        {
            //int dice = rand() % 54;
            //population[i][j] = gens[dice];
            population[i][j] = a[0];
        }
        printf("%2d. : %s\n",i+1,population[i]);
    }

    return 0;
}

但输出结果出现异常(乱码或多余字符),我不擅长二维数组,希望分析错误原因并得到解决方法。

错误原因分析

  • 字符串缺少终止符
    C语言中,printf("%s")打印字符串时,必须以\0(空字符)作为结束标记。你的population数组定义为[20][5],每个个体的数组长度刚好是5,只能存储5个有效字符,没有额外空间存放\0。打印时printf会越界读取内存中的随机数据,导致输出乱码。

  • 字符池索引计算错误
    字符池gens包含26个小写字母、26个大写字母和1个空格,共53个字符。如果启用随机生成代码,rand() % 54会产生0-53的索引,而gens的最大有效索引是52,这会导致越界访问非法内存。

修正方案

1. 调整数组长度,预留终止符空间

将population和nextPopulation的定义修改为:

char population[pop][genCount + 1];
char nextPopulation[pop][genCount + 1];

每个个体数组长度改为6,前5位存有效字符,最后1位存\0。

2. 手动添加字符串终止符

在每个个体的字符赋值完成后,添加\0:

for(int i=0;i<pop;i++)
{
    for(int j=0;j<genCount;j++) // 简化循环条件,等价于j<=genCount-1
    {
        // 动态获取字符池长度,避免手动计数错误
        int gensLen = strlen(gens);
        int dice = rand() % gensLen;
        population[i][j] = gens[dice];
        // 测试阶段可保留a[0]赋值:population[i][j] = a[0];
    }
    population[i][genCount] = '\0'; // 添加字符串终止符
    printf("%2d. : %s\n",i+1,population[i]);
}

3. 优化字符池索引计算

用strlen(gens)动态获取字符池长度,避免手动计数出错,确保随机索引始终在有效范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:20:23