C로 성적 표를 작성하려고합니다. 그러나 포인터를 처리하는 데 미숙하지만 콘솔에 값을 인쇄 할 때 이상한 값을 얻고 있습니다. 내 코드는 다음과 같습니다.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;
}
}
문제는 이름과 등급이 때로는 제대로 표시되지 않는 것입니다. 나는 이것이 포인터와 관련이 있다는 것을 알고있다. 그러나 나는 어떤 오류라도 발견 할 수 없다. 누군가 나를 도울 수 있을까요? 감사.
한 가지 문제는'문자 * tmp를 선언합니다. 정적으로'tmp' ('char tmp [XXX];')를 선언하거나'malloc'으로 실제 포인터를 동적으로 할당해야합니다. – lurker
기본적으로 포인터가 가리키는 곳을 항상 알아야합니다. 루프, 당신은 포인터'tmp'가 가리키는 곳을 모른다. – pmg
@mbratch 모든 변수에 디폴트 값을 부여하는 것이 좋을까? – LanceHAOH