2

I seem to be more of a noob in C++ than I originally thought. As far as my knowledge of C/C++ goes, this should work. I define a character array then try to assign a pointer to the beginning... What am I doing wrong?

// Create character array
char str[] = "t xtd 02 1CF00400 08 11 22 33 44 55 66 77 88 0   0 1234.567890";
// Assign pointer to beginning of array
char* p = &str;
Eric Fossum
  • 2,395
  • 4
  • 26
  • 50

3 Answers3

10

The type of str is char[63]. For reference, note that the type of the string literal itself is const char[63], not const char *. You take the address of that, which gives you a pointer to char[63], or char (*)[63]. You then try to assign that to a char *.

What you should do is not take the address and let the array decay into a pointer:

char *p = str;

What you should really do, though, is use std::string.

chris
  • 60,560
  • 13
  • 143
  • 205
  • Your answer is well defined, but can you help me understand a little more? Are you saying that my char array is made into a constant? – Eric Fossum Nov 04 '12 at 16:51
  • 2
    @EricFossum, It takes the literal, which is an array of constant characters, **copies** them into an array of non-constant chars (which is ok because they're copied), which you then use with your pointer. I felt the need to explicitly say that the literal isn't a pointer, it's an array, as so many people don't know that (as I've seen from 10k+ rep people giving wrong answers when that question was asked a few months ago). – chris Nov 04 '12 at 16:53
5

You can simply omit the address operator,

char *p = str;

works, arrays automatically decay into pointers to the first element in that context. Or, if you wish, explicitly cast, but that would be an abomination.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1
 char* p = str;

The ampersand is redundant. A plain array name just denotes an address of it's beginning.

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65