Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: cannot convert ‘char (*)[63]’ to ‘char*’ in initialization

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;
like image 694
Eric Fossum Avatar asked Jan 30 '26 16:01

Eric Fossum


2 Answers

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.

like image 197
chris Avatar answered Feb 02 '26 04:02

chris


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.

like image 29
Daniel Fischer Avatar answered Feb 02 '26 06:02

Daniel Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!