我是一般的编程新手C,特别是.我正在尝试编写一个使用结构数组的程序,但是如果该结构包含字符串,我遇到了问题.在用户给出最后一个输入后,编译器会以某种方式崩溃.
下面的结构只是一个只包含一个项目的简化版本,因为问题似乎是将字符串读入数组.非常感谢任何帮助,提前谢谢.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* name;
}student;
int main()
{
int size;
printf("enter number of entries\n");
scanf("%d" , &size);
student* all=malloc(size*sizeof(student));
int i;
for(i=0;i<size;i++)
{
printf("enter name\n");
scanf("%s" , all[i].name);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在进行输入之前 scanf("%s" , all[i].name);,您需要分配内存all[i].name.
一个例子-
for(i=0;i<size;i++)
{
all[i].name=malloc(20*sizeof(*(all[i].name)));
if(all[i].name!=NULL){
printf("enter name\n");
scanf("%19s" , all[i].name);
}
}
//use these strings
for(i=0;i<size;i++){
free(all[i].name); //free the allocated memory
}
free(all);
Run Code Online (Sandbox Code Playgroud)
或者在你的结构中代替char *,声明name为char数组(如果你不想使用动态分配) -
typedef struct{
char name[20]; //give any desired size
}student;
/* no need to free in this case */
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
381 次 |
| 最近记录: |