3

C++ code

string *stra;
string strb = "ABC";
stra = &strb;
std::cout <<  stra[0][1] << std::endl;
std::cout << *stra << " " << stra[0]<< std::endl;

why use stra[0] is print same at *stra or why I can use like that

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Nefertari
  • 33
  • 3
  • 1
    Does this answer your question? [Accessing value of array using pointers](https://stackoverflow.com/questions/59185973/accessing-value-of-array-using-pointers) – MikeCAT Apr 05 '21 at 11:29
  • `A[B]` is defined as `*((A)+(B))`. ([N3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) 5.2.1 Subscripting) – MikeCAT Apr 05 '21 at 11:30

2 Answers2

2

According to the C++ 14 Standard (5.2.1 Subscripting)

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type. The result is of type “T.” The type “T” shall be a completely-defined object type.64 The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. — end note ], except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.

So the expression stra[0] is evaluated like *( stra + 0 ) that is the same as *stra.

Pay attention to that as the operation + is commutative then this expression *( stra + 0 ) is the same as *( 0 + stra ). That means that you may even write 0[stra] instead of stra[0].

Here is a demonstrative program that instead of objects of the type std::string uses string litarals.

#include <iostream>

int main() 
{
    std::cout << "Heelo"[0] << ' ' << *"Hello" << '\n';
    
    return 0;
}

The program output is

H H

String literals in C++ are represented by constant character arrays. For example the string literal "Hello" is stored like an unnamed character array

const char unnamed_string_literal[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

Used in expressions with the dereferencing operator * or the subscript operator [] they are converted to pointers to their first elements of the type const char *. Thus this statement

    std::cout << "Heelo"[0] << ' ' << *"Hello" << '\n';

outputs the first character of the string literal "Hello".

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

By definition (as also said @MikeCAT) operation A[B] (for plain arrays) is defined as *(A + B).

This is operation of array indexing - obtaining value of array's element. In C/C++ plain arrays are often represented just by a pointer. This operation allows reading value of array A at B'th index.

Just dereferencing operator *A is same as saying *(A + 0). Hence A[0] does same as just *A.

Arty
  • 14,883
  • 6
  • 36
  • 69