我正在创建一个系统,用于将学生姓名和分数输入数组并将相同的信息打印到屏幕上,不幸的是,我一直得到奇怪的输出。
我使用调试器逐步完成了我的程序,它表明一切运行顺利,直到我到达打印学生信息的函数,双指针 char 数组的值弄乱了。
这是我运行程序时看到的图像。( http://s28.postimg.org/nv29feawt/Error.png )
注意:虽然我知道有更好、更简单的方法可以做到这一点,但我需要使用动态分配的内存和数组来完成此分配。
int main(void)
{
char **firstNames;
char **lastNames;
float *scores;
int recordsLength;
printf("Please indicate the number of records you want to enter: ");
scanf("%d", &recordsLength);
printf("\n\n");
firstNames = (char **)malloc(recordsLength * sizeof(char *));
lastNames = (char **)malloc(recordsLength * sizeof(char *));
scores = (float *)malloc(recordsLength * sizeof(float));
int i = 0;
while(i < recordsLength)
{
createNewEntry(i, firstNames, lastNames, scores);
i++;
}
printEntry(0, firstNames, lastNames, scores);
free(firstNames);
free(lastNames);
free(scores);
return 0;
}
void clearScreen()
{
#ifdef _WIN32
system("cls");
#elif _unix_
system("clear");
#endif
}
void printEntry(int entryID, char *firstNames[], char *lastNames[], float scores[])
{
clearScreen();
printf("|-------------------------------------------------------------------------|\n");
printf("| Student Entry |\n");
printf("|-------------------------------------------------------------------------|\n|\n");
printf("| First Name: %s Last Name: %s Score: %.1f\n|\n|\n|\n", firstNames[entryID], lastNames[entryID], scores[entryID]);
printf("|-------------------------------------------------------------------------|\n");
printf("| |\n");
printf("|-------------------------------------------------------------------------|\n\n");
}
void createNewEntry(int index, char *firstNames[], char *lastNames[], float scores[])
{
printf("Please input the records of the new student.\n\n\n");
char first[20];
char last[20];
float score = 100.0f;
printf("Please enter the student's first name: ");
scanf("%s", &first);
printf("\n\n");
printf("Please enter the student's last name: ");
scanf("%s", &last);
printf("\n\n");
printf("Please enter the student's score: ");
scanf("%f", &score);
printf("\n\n");
firstNames[index] = (char *)malloc((strlen(first)) * sizeof(char));
firstNames[index] = first;
lastNames[index] = (char *)malloc((strlen(last)) * sizeof(char));
lastNames[index] = last;
printf("first name: %s", firstNames[index]);
printf("last name: %s", lastNames[index]);
scores[index] = score;
}