3

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.

Ren
  • 4,594
  • 9
  • 33
  • 61

3 Answers3

3

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

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

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

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.

Pochi
  • 2,026
  • 1
  • 15
  • 11
  • All of this is pretty good, except for the part where you say an array is a pointer, which it isn't. – Carl Norum Feb 01 '12 at 00:48
  • All is great, but I made them equal because that was the intent. I was wondering if doing something `_password = password;` would simply copy the value or also refer to the same address. Therefore my two examples with different names but same content. – Ren Feb 01 '12 at 01:05
  • An array as a data structure is not a pointer, but the representation of the label associated is a pointer. The structure of the label has a bit more than just a pointer in some instances, but you can make an array C-style using malloc. – Pochi Feb 01 '12 at 09:10