Olivier Pons
Olivier Pons

Reputation: 15778

what is the difference between &c and *c declaration?

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];

?

Upvotes: 3

Views: 4890

Answers (3)

Grigor Gevorgyan
Grigor Gevorgyan

Reputation: 6853

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.

Upvotes: 1

littleadv
littleadv

Reputation: 20272

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.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182769

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..

Upvotes: 0

Related Questions