0
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.

6
  • 1
    char pointers are not arrays. Commented Mar 27, 2016 at 20:36
  • To start with, they have to point to something valid before you dereference them, eg. try to write through them. Commented Mar 27, 2016 at 20:36
  • Really? Guess my understanding is weak then. I read that arrays are just pointers. Commented Mar 27, 2016 at 20:37
  • If you read that on a site, delete the bookmark and/or history. If it's in a paper book, apply gasoline and a match. Commented Mar 27, 2016 at 20:38
  • @MartinJames we don't need anymore global warming. A shredder will do just fine. :P Commented Mar 27, 2016 at 20:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

How do I know how much memory I give to p if I don't know the input length from the user?
@qaispak You must be knowing the length, otherwise how do you suggest the array worked?
Sorry, by that I actually meant: "The array (when I know the length), I can get input but I want to know how to get it if I don't know the length... which I assumed is when we use pointers (but I am wrong since we need to define length for pointers as well)
@qaispak yes, fgets() wont allocate memory to the pointer. You need to allocate memory prior to passing the pointer.
Yes I understand that, but how do I know how much memory to allocate?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.