i have written this code to copy 5 names in a structure
#include<conio.h>
#define loop_count 5
char copy_name(char *);
typedef struct{
int count;
char name[3][20];
}student;
student *p; //declare structure pointer;
int main()
{
student s; //declare variable of type student ;
p=&s; //giving p address of s;
p->count=0; //initialize p->count value 0;
char input_name[20]; // an array to input names;
int i;//i for loop count;
for(i=0;i<loop_count;i++){
fgets(input_name,20,stdin);
copy_name(input_name); //call function ;
if(p->count==loop_count)//for breaking the loop when (p->count==5);
break;
}
for(i=0;i<loop_count;i++){
printf("%s",p->name[i]);//print the names copied in structure;
}
getch();
}
char copy_name(char *q){
strncpy(p->name[(p->count)++],q,20);//copy names inside structure;
}
my question is here
strncpy(p->name[(p->count)++],q,20);
first name is copied to p->name[0]; then when we input the next name if it is not incremented to p->name[1] after copying p->name[0]; it (p->name[0])should be over written. if it is not then when it is incremented to next array p->count[1] ??
if it is incremented to p->name[1] after copying p->name[0]; then after copying fourth name the value of p->count will be 4. for this the loop will break cause(p->count==loop_count==5) and we cannot copy the fifth name.
please help.