char str[] = "asdf"; cout << str << endl; *str = "qwer"[2]; cout << str << endl; *(str+2) = "qwer"[1]; cout << str << endl; 

Displays accordingly

asdf esdf eswf

Excites the place *str = "qwer"[2]; How does this design work? What type is the quoted string - to char* or to string ?

  • Is it a classic C ++ or .NET c ++ (CLI) ??? otherwise it can all change a lot. - KoVadim
  • And in fact, g ++ does not compile at all. @pol, what did you use? - avp
  • To char. But str is a pointer, and you write the value char to it. Ayayaya ... Check out my blog for articles on this topic. Link in profile. - Jakeroid
  • @Jakeroid was incorrectly inserted there ... fixed. - Pavel
  • @KoVadim and @avp are compiled into gcc - only the hashcode ate pointers before str, probably because of this and you do not compile) - Pavel

5 answers 5

"something" is a string literal. It has type const char* - a constant pointer to the area where the string is stored. Indexing in this string is the same as in a regular C-array, it ends with a null character.

UPD : I apologize, inattentively read the question. This design does not work, because str is of type array array of size 5 and can not be changed. Especially assigning to char . KoVadim wrote correctly, but for some reason he was zaminusovali.

  • @zhzhioev everything works perfectly) - Pavel

This construct does not work and should not be compiled. str = "qwer"[2]; - this is an attempt to assign a character to a pointer to an array of characters ... gcc swears at this very much (incompatible types in assignment of 'const char' to 'char [5]')

    autoboxing to char 'y

       str = "qwer"[2]; 

      Here you have a str - a pointer to char ( char * ), while it points to the 0th position of the array you created. "qwer"[2] - takes char (constant, const_char ), and assigns it to the value at the address str, that is, the element at the 0th position.

        str is a pointer to the first element of the array. That is, * str is the first element itself. "qwer" is a constant array. Writing str = "qwer" [2] - you "tell" the compiler that you need to take an element of type char from the constant array "qwer" * at number 3 (because the first element is number zero, and the third is with index 0 + 2) and put in str , that is, in the first element of the str * array . Why from scratch? The array index is the offset of the pointer from the given position. That is, an array variable is a pointer to the first element, and an index is an offset.