gpt4 book ai didi

c - C中的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:43 24 4
gpt4 key购买 nike

我需要在一个二维数组中维护五个学生的名字。每个学生姓名的长度可以为 20 个字符。如果第六个学生条目出现,则第一个将被替换,第七个将替换第二个,依此类推。

下面是我的程序。当我为第二个学生调用 set 函数(在二维数组中添加学生记录)时,请告诉我为什么我的第一个学生记录被替换。

我根据您的建议更新了代码,但仍然无济于事。请提出建议。

#include <stdio.h>
#include<strings.h>

void display(char s[][21]);

void set(char stuName[][21],char* merchantNo)
{

for(int i = 0;i<5;i++)
{
if(stuName[i][21] == '\0')
{
strcpy(stuName[i], merchantNo);
break;
}
}
}

void display(char s[][21])
{
for(int i = 0;i<5;i++)
{
printf("s[%d] is [%s]\n",i,s[i]);
}
}

int main()
{
char stuName[5][21];

printf("sizeof(stuName) is [%d]\n",sizeof(stuName));

memset(stuName,'\0',sizeof(stuName));

display(stuName);

set(stuName,"Student1");
display(stuName);

set(stuName,"Student2");

display(stuName);

return 0;
}

输出

s[0] is []
s[1] is []
s[2] is []
s[3] is []
s[4] is []
s[0] is [Student1]
s[1] is []
s[2] is []
s[3] is []
s[4] is []
s[0] is [Student2]
s[1] is []
s[2] is []
s[3] is []
s[4] is []

最佳答案

看起来您需要将您的 set 函数修改为:

int set(char stuName[][21], char* merchantNo)
{
int l = strlen(merchantNo);
if (21 <= l) // input name is greater than your array
return -1;

for (int i = 0; i < 5; i++)
{
if (stuName[i][0] == '\0')
{
strncpy(stuName[i], merchantNo, l);
return i; // return the position where you've added
}
}
return -2; // array full, can't add new entry
}

关于c - C中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6414028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com