【发布时间】:2021-10-17 19:56:44
【问题描述】:
typedef struct info{ //main record
int *id;
unsigned char *name;
}student;
void create(){
student *s_ptr;
int num_of_student,i;
FILE *f_ptr;
f_ptr = fopen("studentdata.txt","w");
printf("**How many student to record**\n");
printf("Enter:");
scanf("%d",&num_of_student);
s_ptr = (student*)calloc(num_of_student,sizeof(student));
for(i=0;i<num_of_student;i++){
printf("Enter student id: ");
scanf("%d",&s_ptr[i]);//while string format is %d it prints char value to the file.
fflush(stdin);
printf("Enter student full name: ");
scanf("%[^\n]",&(s_ptr+i)->name);
fwrite(s_ptr+i,sizeof(struct info),1,f_ptr);
}
}
scanf("**%d**",&s_ptr[i]) 在文件中打印其相对字符值,但在将字符串格式从 %d 更改为 %s 后,它会打印实际的 int 值。为什么?
【问题讨论】:
-
循环中的两个
scanf语句和student结构都是错误的。为什么你的结构包含指针?为什么不为这些指针分配任何内存指向?为什么第一个 scanf 使用结构本身的地址而不是结构中的变量?摆脱指针并修复第一个 scanf 以读入id变量然后看看你有什么。 -
scanf格式字符串中的类型与参数不匹配。name应该是char*而不是unsigned char*。最好从一个更简单的程序或最小的可重现示例开始,然后从那里扩展代码。 -
我刚开始熟悉指针,所以我尝试了这种方式,但现在我知道数组更适合字符。感谢您的评论。