Home > Software engineering >  Need Help in understanding what my book's error example means
Need Help in understanding what my book's error example means

Time:11-28

So here is the code:

#include <stdio.h>

int main() {
    char str1[] ="Hello", str2[20] ="Hi";
    char *p ="Hello", *s ="Hi";
    str1 = "Adieu";
    return 0;
}

Now my Book gives this reason

error, constant pointer cannot change

And when I run it, I get error as :

error: assignment to expression with array type

My question is why does my book says so ?, From where did pointers come here ?

The book is Let us C 18th edition (latest edition at the time the question was posted) by Yashavant P. Kanetkar incase you need refence.

CodePudding user response:

In the line

str1 = "Adieu";

the array str will decay to a pointer to the first element of the array, which is an rvalue (not an lvalue) and therefore cannot be modified.

This behavior is specified in §6.3.2.1 ¶3 of the ISO C11 standard:

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. [...]

Note that in the quote above, "initialize an array" means initialize it inside a declaration, not assign it a value outside a declaration (which would be an "assignment", not an "initialization").

For this reason, the error message in your book

error, constant pointer cannot change

is correct. An rvalue cannot be modified and it is therefore not wrong to describe it as "constant".

However, the error message from your compiler

error: assignment to expression with array type

is also correct and probably more useful.

CodePudding user response:

str1[] = "Hello";

str1 is a character array which has been initialized from a string literal. It has automatic storage duration and is modifiable. The string literal "hello" on the other hand, is placed in the text segment(read-only-memory), although the compiler may choose not to, and as such it's illegal to modify it, and doing so results in undefined behaviour. str1[ ] on the other hand, stores a copy of the literal. So you're only modifying the copy, not the literal itself. But C doesn't allow you to modify it like this:

str2 = str1;

You can modify it by assigning a single element at a time or by using string functions such as strcpy, strnpcy, et cetera declared in the string.h header file to copy one string to another string. Or you may use a pointer to a character, which is modifiable and can be changed to point to some other location in memory.

As of that book, it's infamous here, being the cause of too many errors on stackoverflow. The author has an incomplete understanding of the language. Consider picking up another book, preferably from The Definitive C Book Guide and List.

  • Related