char array in C++ - expression must be a modifiable lvalue

Hello,

Could you please explain why we have an erorr?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace  std;

int main()
{
	char s[80];
	cin.getline(s, 80);

	while (*s != '\0')
	{
		cout.put(char(tolower(*s)));
		s++; // error
	}
	return 0;
}

.
Incrementing (++ operator) an array makes no sense. An array is not a pointer, although an array will degrade into a pointer if you are using it by value.

Copy the array's pointer to another variable first, e.g.
1
2
3
4
5
char* ptr = s;

// ...

ptr++;
Last edited on
Thank you, but the name of an array is the pointer of the first element. isn't it?
No, not really, though it seems a lot of schools teach that these days.

An (unindexed) array name will point to the address of the first element, but an array is not a pointer, and shouldn't be treated as one. Your program would benefit from a char pointer that is initialized to the first element of the array, and advanced within your while loop.
Thank you, but the name of an array is the pointer of the first element. isn't it?


the c++ language ensures that the compiler converts the name of an array to a pointer for you no questions asked. So syntactically, yes, it may as well be, for a rather limited scope of things you can do with it. Its more like a heavily constantified pointer that you can't new, delete, assign, move, or much else -- all it gives you is a memory address where you can look around.

More technically and precisely, no, it isn't. Consider this: you can use [] on a pointer. Does that make a pointer an array? (spoiler: no).

Think of it as just a shortcut to avoid having to type &array[0].
Last edited on
^good analogy, it's very much like avoiding "&array[0]", because just like how arr++ doesn't work, neither would (&array[0])++ (trying to increment a temporary value).
Topic archived. No new replies allowed.