我试图用C编写一本成绩册。但是,由于我在处理指针方面的经验不足,当我将值打印到控制台时,我得到了奇怪的值。我的代码如下:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main(int agrc,char * argv[]) {
// Create null pointers
char * students = 0;
char * grades = 0;
int * namelen = 0;
// Variable to track class size
int classSize = 0;
printf("Please enter the class size: ");
scanf("%d",&classSize);
printf("Class size = %d\n",classSize);
// Allocate the memory for the null pointers
students = malloc(classSize * sizeof(char)+classSize);
grades = malloc(classSize * sizeof(int));
namelen = malloc(classSize * sizeof(int));
int i = 0;
char * tmp;
int pos = 0;
for(;i<classSize;i++) {
printf("Please enter student %d's name: ",i+1);
// Read name into dummy variable
scanf("%s",tmp);
// Store the length of the name
*(namelen + i) = strlen(tmp);
// Read in the name of the student
strcpy(students+pos,tmp);
printf("Please enter %s's grade: ",students + pos);
// Read in the grade of the student
scanf("%d",grades+i);
pos += *(namelen+i)+1;
}
printf("\n");
printf("The data that you entered is as follows:\n");
printf("----------------------------------------\n");
i = 0;
pos = 0;
for(;i<classSize;i++) {
printf("Student %d: %s. Grade: %d\n",i+1,students+pos,*(grades+i));
pos += *(namelen+i)+1;
}
}
问题是,有时学生的名字和成绩没有被正确地显示出来。我知道这和指针有关。但我似乎看不出任何错误。有人能帮帮我吗?谢谢。
最佳答案
students = malloc(classSize * sizeof(char)+classSize); // allocates one char for each student name.
这应该替换为每个名称的预期大小。
students = malloc(classSize * sizeof(char) * 20); // assuming size of each to max of 20 bytes including null termination.
char * tmp;
这应该是
char tmp[20]; // assumed max size of each name is 20 bytes including null.
关于c - C成绩簿中的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22936679/