简体   繁体   中英

Using fgets to store character pointer program crashes

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM