English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Consider the following snippet.

#include

int main()
{
char x[] = "Hello";
char *y = "Hello";

x[0] = 'J';
y[0] = 'J';
}

Assignment to x[0] is fine, but assignment to y[0] is not.
Does anyone know the "formal" reason?

2007-05-01 06:43:10 · 3 answers · asked by AC 1 in Computers & Internet Programming & Design

3 answers

because the variable "y" is defined as a pointer to a char array. where "x" is a char array.

the way to assign the letter "J" to those locations is:
for "x":
x[0] = 'J';

for "y"

*y = 'J';
or
*(y + 0) = 'J';

2007-05-02 01:44:14 · answer #1 · answered by justme 7 · 0 2

See http://c-faq.com/decl/strlitinit.html
On a side note, google C++ FAQ and C FAQ and bookmark them. They are very comprehensive.

So, basically, y points to a read only section of memory. You can read y[0], but you can't change it.

2007-05-01 13:59:42 · answer #2 · answered by csanon 6 · 1 1

Formal reasoning is as follows:

10011 011110 0111101101 111101 11011101 00001 01 01111 011000 0100000 000000001 0010001000101 1001 0110 11010101001 01111101

2007-05-01 13:51:24 · answer #3 · answered by Anonymous · 0 4

fedest.com, questions and answers