使用与fgets存储字符指针程序崩溃 [英] Using fgets to store character pointer program crashes

查看:776
本文介绍了使用与fgets存储字符指针程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的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 to p before you can read/write something to/from the memory location pointer by p.

这篇关于使用与fgets存储字符指针程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆