3

I don't understand: What is the difference between:

string Str ("Str");
char &C = Str [0];

and this:

string Str ("Str");
char *C = Str;

I don't understand this declaration actually:

char &C = Str [0];

?

Olivier Pons
  • 15,363
  • 26
  • 117
  • 213

3 Answers3

1

Differences between pointer (char* C) and reference(char &C):

  1. Reference must be initialized at once, while pointer might not - you cannot just write char &C, you must write char &C = ...;, but char *C; is ok.
  2. Once initialized, reference cannot change the address it refers to, while pointer can.

In other words, pointer can have a NULL-value and arithmetic operations can be performed with pointers.

Also char &C is in a manner equal to char * const C.

Grigor Gevorgyan
  • 6,753
  • 4
  • 35
  • 64
  • Thank you very much, I have to "mix" between your answer and other ones, but yours is kinddof "clearer" to me. Thanks again – Olivier Pons Nov 02 '11 at 08:59
0
char &C = Str [0];

This makes C a reference to Str[0]. A reference is another way to access a variable. It's basically just a more elegant way to do the same thing pointers do. There are some differences..

Community
  • 1
  • 1
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0
char &C = Str [0];

This references c to the first member of the Str. Accessing c will access Str[0].

char *C = Str;

Here, c points to the first member of the Str. Accessing c will not access Str[0]. Accessing *c will.

littleadv
  • 20,100
  • 2
  • 36
  • 50