I am rather new to C and am probably doing something stupid but I can’t find out why my string array isn’t keeping the previous values while the grade is keeping all the values entered:
for(int i=0; i <noOfStudents; i++)
{
do{
printf("Please enter Student Full Name.");
//read string till enter
scanf(" %[^\n]", &studentFullName);
if(studentFullName == "")
{
printf("Invalid Student Name!\n\n");
getchar();
}
else
{
names[i] = studentFullName;
validStudentName = 1;
}
}while(validStudentName != 1);
do{
printf("Please enter Student Grade.");
scanf_s(" %d", &grade);
if(grade < -1 && grade >100)
{
printf("Invalid Student Grade!\n\n");
getchar();
}
else
{
grades[i] = grade;
validGrade = 1;
}
}while(validGrade != 1);
printf("\n");
}
gradeis an integer. When you do:then
acontinues to be 3, because integers are copied.studentFullName is, however, a pointer. Just like integers, pointers are copied. However, the data the pointer points to is not. So, basically, you’ve got your entire names[] array as a bunch of pointers, all pointing to the exact same data.
There are several functions that will copy the pointed-to data for you, the one you’re looking for is probably
strdup. Note that you mustfreeall the pointers you get back fromstrdup.