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

C语言二维数组存储学生字符串时的字符覆盖问题求助

问题分析与解决

你的代码出现字符串混入的问题,核心原因是数组类型定义错误,导致字符串存储时发生栈内存溢出:

原代码中char *arr[nmbStud][256];是一个二维指针数组,每个元素都是char*类型的指针(64位系统下占8字节)。你没有给这些指针分配内存,直接用&arr[rows][columns]作为scanf的写入地址,相当于把字符串直接写到了指针变量的内存空间里。当输入的字符串长度超过8(加上字符串结束符'\0'共9字节)时,就会溢出到相邻的指针变量空间,覆盖后续数据,导致出现字符串混入的情况。

修正方案

1. 修正数组定义

将二维指针数组改为三维字符数组,直接为每个学生的3项数据分配足够的字符空间:

char arr[nmbStud][3][256];

这里arr[rows][columns]就是对应第rows+1个学生的第columns项数据的字符数组首地址,无需额外取地址。

2. 修复scanf调用

去掉&符号,同时为了防止输入过长再次溢出,限制scanf的输入长度(最多255字符,留1位存'\0')。

3. 简化循环逻辑

原代码里的while(columns < 3)完全多余,直接用顺序赋值即可。

修正后的完整代码

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

int main() {

  int nmbStud;
  int rows, columns;

  printf("Enter the number of students you want to add : ");
  scanf("%d", &nmbStud);

  // 定义三维字符数组:nmbStud个学生,每个学生3项数据,每项最多255个字符+结束符
  char arr[nmbStud][3][256];

  for (rows = 0; rows < nmbStud; rows++) {
      printf("--Enter the %d name : ", rows + 1);
      // 限制输入长度为255,避免溢出
      scanf("%255s", arr[rows][0]);

      printf("--Enter the %d family name : ", rows + 1);
      scanf("%255s", arr[rows][1]);

      printf("--Enter the code of the student %d : ", rows + 1);
      scanf("%255s", arr[rows][2]);
  }

  // 输出数据
  for (rows = 0; rows < nmbStud; rows++) {
      printf("Student %d:\n", rows + 1);
      printf("--->Name: %s\n", arr[rows][0]);
      printf("--->Family Name: %s\n", arr[rows][1]);
      printf("--->Code: %s\n", arr[rows][2]);
  }
  return 0;
}

关键说明

  • 三维字符数组arr[nmbStud][3][256]:第一维度对应学生数量,第二维度对应每个学生的3项数据(name/fname/code),第三维度是每个字符串的最大长度(256)。
  • scanf("%255s", ...):限制输入的字符数不超过255,确保不会超出数组的存储空间,从根源避免缓冲区溢出问题。
  • 去掉了冗余的while循环,代码逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:55:18