I need to maintain five students' names 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 []