使用结构指针读取字符串时c中的结构指针问题 [英] structure pointer problem in c when reading string using structure pointer
本文介绍了使用结构指针读取字符串时c中的结构指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
struct book
{
char name[50];
char author[50];
int page;
float price;
};
int main()
{
struct book *x;
printf("name : ");
gets(x->name);
printf("author : ");
gets(x->author);
printf("page : ");
scanf("%d",&x->page);
printf("price : ");
scanf("%f",&x->price);
printf("\n%s\t%s\t%d\t%f",x->name,x->author,x->page,x->price);
getch();
return 0;
}
这段代码无法正常工作,并给出了分段错误
this code is not working properly and giving a segmentation fault
推荐答案
我对它给出分段错误并不感到惊讶.在main
中,您拥有;
I''m not surprised it gives a segmentation fault. Inmain
you have;
struct book *x;
printf("name : ");
gets(x->name);
...
因此,您已经创建了指针x
,但是它没有指向任何内容,因此存在段错误.您需要对其进行初始化,以便它指向实际的内存结构.这是通过调用malloc
来完成的,因此:
So you have created the pointer x
but it does not point to anything, hence the seg fault. You need to initialise it so that it points to an actual memory structure. This is done by a call to malloc
thus:
struct book *x;
// allocate a new book structure on the heap
x = (struct book *)malloc(sizeof(struct book));
printf("name : ");
gets(x->name);
您没有初始化结构指针x
.我猜您正在通过查看问题标签来使用C ++.用这种方式做.
You didn''t initialize the structure pointerx
. I guess you''re using C++ by seeing your question''s tags. Do it in this way.
struct book *x;
x = new book;
printf("name : ");
.....
这篇关于使用结构指针读取字符串时c中的结构指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文