Two dimensional array in C
I need to maintain five students' nam开发者_如何学运维es in a two dimensional array. Each student name can be 20 characters long. If the sixth student entry came, then the first will be replaced, seventh will replace second and so on.
Below is my program. Please let me know when I am calling the set function( to add a student record in a 2D array) for the second student, why my first student record is replaced.
I updated the code as per your suggestions, however still it doesnt helps. Please suggest.
#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;
}
Output
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 []
Looks like you need to modify your set function to something like:
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
}
If you have five student names, you should declare an array of five:
char stuName[5][21];
Remember that an array of N, T x[N]
, has valid members x[0]
up to x[N-1]
.
char stuName[4][21];
This should be char stuName[5][21]
if you expect to be able to hold names for 5 students.
Also, your test for an empty name is wrong:
if(stuName[i][21] == 0x00)
strcpy(stuName[i], merchantNo);
That should probably be something like stuName[i][0] == 0
.
And the break
after those lines will always be executed, so you'll never go through the for
loop in set()
more than once. That's what's causing the problem you mentioned.
Another thing: be careful when you use strcpy. A name that's too long will cause strange things to happen. You might want to look into strncpy.
You want to check stuName[i][20], stuName[i][21] to see if the last character is null. However, even when you write the first name, the last character is still null. You will need to keep some kind of counter to check what name you are up to.
Also, the if in the set function should have squiggly braces to include the break, otherwise it will always break when i=0.
精彩评论