0

It is my understanding that fgets() returns the string parameter that is input, however,

I'm receiving "error: incompatible types when assigning to type 'char[101]' from type 'char *'",

So, why is the variable 'line' considered type 'char[101]' and not type 'char *' ?

char line[101] = "";

while (feof(filePtr) == 0){
    line = fgets(line, 101, filePtr);
    strcpy(strPtr, line);
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

5

Long story short: You cannot assign to an array, it's not a modifiable lvalue. You need to define another pointer to hold the return value.

why is the variable line considered type char[101] and not type char *

In your case, line is not considered to be of type char [101], it is indeed. In some of the cases, array decays down to a pointer to the first element in the array, but that does not change the fact that the array variable itself is of array type.

That said, you're overdoing it. You don't need to store the return value there. You can just check it against NULL and get done with. fgets() stores the scanned value in the line array anyways. That's the whole point of passing line (and it's size) in the first place.

That said, please see Why is “while ( !feof (file) )” always wrong?

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

There are two points to be clarified here:

  • You don't need to get the result of fgets() call in the array pointer. The first parameter of fgets() is the array to be used to store the read values. You can create any temporary char pointer and get the result of fgets() into it. This pointer will only be used to detect fgets() errors if it's value is null.

  • Array name in c can not be assigned any values. As it's in some cases treated as a pointer to the array first element, it can be misunderstood. Also as the compiler know the size of the array at compile time it uses this information. If you used sizeof(line) the output will be 101 instead of 4 which should be the case of sizeof(any pointer) in a 32 bit machine or 8 in 64 bit machines.

  • 2
    It's tricky, but an array name is not a pointer; it is the name of an array. In many contexts, it changes into a pointer to the first element of the array, but not all (`sizeof` is the well-known one; `_Alignof` is less well-known). An array name (as distinct from an array-like function parameter) is not a modifiable lvalue; you cannot assign to it. But strictly that isn't because it is a constant pointer, though it is moderately similar. – Jonathan Leffler Mar 04 '17 at 17:21
  • @Jonathan Leffler I modified my answer according to your comment. – وليد تاج الدين Mar 04 '17 at 17:28