I'm confused about the use of the dereference operator in the declaring of char arrays.
I think I understand that the dereference operator is used to dereference memory addresses to their values, and also in an unrelated function in the declaration of pointers; and that arrays are like special pointers to memory addresses.
But why is the * operator used in declaring char arrays, e.g.:
char * carr = "Hello";
Why doesn't the following work, and instead give a series of "invalid conversion from `const char*' to `char'" errors?:
char carr[5] = {"H", "e", "l", "l", "o"};
Why are char arrays different than say int arrays?
Double quotes represent strings, single quotes represent chars. Try changing the below code from double quotes to single:
char carr[5] = {"H", "e", "l", "l", "o"};
to
char carr[5] = {'H', 'e', 'l', 'l', 'o'};
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
Some arrays...
int arr[ ] = { 1, 2, 3 };
double arr[ ] = { 1.0, 2.0, 3.0 };
char arr[ ] = { '1', '2', '3' };
A char array (and only char arrays), can also be initialised like this (for convenience) char arr[ ] = "123";
Finally, also for char only, is a pointer to a string constant char *arr = "123";
A pointer to a string constant is like this to the compiler.
const char anonymous[ ] = "123";
char *arr = anonymous;
the only difference being is that you never get to see the anonymous name the compiler generates.
Again, this is a programmer convenience which only applies to char.
If you wanted say a pointer to an integer constant, then you would have to do that the long way by yourself.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
> Didn't work for me, it gives a " invalid conversion from `const char*' to `char*'" compile error.
> Would it be correct to say that char *arr = "123"; is like this to the compiler:
The ability to do char *arr = "a string";
is a special case relaxation of the rules. In other situations, the compiler will tell you whether you're breaking 'const-correctness'.
Some time ago, a change was added to the standards to allow"string" constants to be placed in read-only memory (and thus const). But they don't have to be. Another thing the standards people try to do is avoid breaking existing common practice in existing code.
Any new code, and any code being maintained should be writing const char *arr = "a string";
For the moment, you can get away with it, but you should really start using const to be future-proof.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953