C中的分段错误
我正在尝试编写这段代码,但运行程序后出现分段错误,您能帮忙解决一下吗?
#include <stdio.h>
#include <string.h>
typedef struct{
int salary;
char* name;
} employee ;
int main(){
employee p[2];
int i;
for(i=0;i<2; i++){
printf("enter sal ");
scanf("%d", &p[i].salary);
printf("enter name ");
scanf("%s", &p[i].name);
}
for(i=0;i<2; i++){
printf("p %d",p[i].salary);
printf("p %s",p[i].name);
}
return 0;
}
I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out?
#include <stdio.h>
#include <string.h>
typedef struct{
int salary;
char* name;
} employee ;
int main(){
employee p[2];
int i;
for(i=0;i<2; i++){
printf("enter sal ");
scanf("%d", &p[i].salary);
printf("enter name ");
scanf("%s", &p[i].name);
}
for(i=0;i<2; i++){
printf("p %d",p[i].salary);
printf("p %s",p[i].name);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您必须为
employee
每个实例的name
成员保留内存:就在该变量的
scanf
之前。声明指向 charchar*
的指针不会为指向的实际字符串分配内存,而只是为指针本身分配内存,并且在您的示例中它未初始化。通过使用malloc
,您可以保留一块内存并使指针指向它。您必须小心边界检查,因为您必须事先保留内存,足以容纳用户正在写入的内容。You have to reserve memory for the
name
member of each instance ofemployee
:just before the
scanf
for that variable. Declaring a pointer to charchar*
does not assign memory for the actual string pointed to, but just for the pointer itself, and in your example it is not initialized. By usingmalloc
you reserve a piece of memory and makes the pointer point to it. You have to be careful with bounds checking, because you have to reserve the memory beforehand, enough to hold what the user is writing.您需要为结构中的“name”字符串分配内存。使用 malloc() 或通过将 name 声明为给定大小 (char name[SIZE]) 的数组来执行此操作。
You need to allocate memory for the "name" string in your structure. Do this using malloc() or by declaring name as an array of a given size (char name[SIZE]).
p[i].name = (char*)malloc(MAX_NAME_LEN)
scanf("%s", &p[i ].name)
应为scanf("%s", p[i].name)
。p[i].name = (char*)malloc(MAX_NAME_LEN)
scanf("%s", &p[i].name)
should readscanf("%s", p[i].name)
.结构体字段
name
只是一个通配符指针。您正在将用户输入读取为:
到
name
指向的内存中,该内存可以位于任何位置。要解决此问题,您需要动态分配
name
指向的内存,或者可以将name
更改为大小比最大值大一的char
数组名称的长度可能。The structure field
name
is just a wild character pointer.you are reading the user input as:
into the memory pointed by
name
which could be anywhere.To fix this you need to dynamically allocate memory pointed to by
name
or you can changename
to achar
array of size one greater than the max length of the name possible.你不需要 &扫描到指针时的运算符。并且您需要 malloc
p[i].name
You don't need the & operator when scanf'ing to pointer. And you need to malloc
p[i].name
您没有为 char* name 分配内存。更改数据结构
或使用 malloc 分配内存
You are not allocating memory for char* name. change your data structure to
or allocate memory using malloc
您忘记为
p[i].name
分配内存。You forgot to allocate memory for
p[i].name
.