使用与fgets存储字符指针程序崩溃 [英] Using fgets to store character pointer program crashes
问题描述
的char * p;
与fgets(P,10,标准输入);
这是为什么崩溃我的程序?好像我不能使用FGETS字符指针,但因此它没有任何意义,我可以使用数组。
的好像我不能使用FGETS字符指针,但我可以用数组的
块引用>没有,你可以传递,为
在同时使用,只要分配内存的指针与fgets()
。在这种情况下,使用指针,
的char * p;
P
是未初始化,并指出了一些任意的内存位置这是无效的。您需要分配适当的内存P
之前,你可以读/写的东西/从P
的内存位置的指针。char *p; fgets(p,10,stdin);
Why is this crashing my program? Seems like I can't use char pointers in Fgets but I can use arrays so it makes no sense.
解决方案Seems like I can't use char pointers in Fgets but I can use arrays
No, you can use both, as long as you allocate memory to the pointer before passing that to
fgets()
.In this case, using pointers,
char *p;
p
is unitialized and points to some arbitrary memory location which is invalid. You need to allocate proper memory top
before you can read/write something to/from the memory location pointer byp
.这篇关于使用与fgets存储字符指针程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!