Ren
Ren

Reputation: 4683

C++: Pointers value & addresses

So I have the following code:

char userLoginName[] = "Smith";
char password[] = "Smith";
char *_userLoginName, *_password;

_userLoginName = &userLoginName[0]; //1st way
_password = password; //2nd way

Would I be doing the same thing in the two last lines? If not, then why and when would/should I use each of these methods?

EDIT#1: I put the two of them on cout and I had the same result. I don't know how to differentiate them.

Upvotes: 3

Views: 181

Answers (3)

Pochi
Pochi

Reputation: 2196

The reason you're getting the same output for both is that they both point to the same literal (not exactly the same address, though).

Suppose you had this:

char userLoginName[] = "Smithlogin"; 
char password[] = "Smithpass"; 
char *_userLoginName, *_password;

_userLoginName = &userLoginName[0]; //1st way
_password = password; //2nd way

You'd have different outputs for _userLoginName and _password.

The array name is actually a pointer. So userLoginName is a pointer to the first element to an array of chars.

So for the [] operator. Say you have and array called arr. arr[x] is actually *(arr + x). It moves the pointer by the specified amount to point to what you want and dereferences it.

Your two methods of assigning a pointer do essentially the same thing if they are operating on the same array though, but only because you're looking at element 0.

Upvotes: 0

They are basically the same. Arrays when used as rvalues decay into pointers to the first element, so the expression _password = password; is implicitly converted to _password = &password[0];

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 224844

Yes, these two examples are the same. The array password decays to a pointer to its first element in your second example, so they're semantically identical.

Upvotes: 3

Related Questions