Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char, pointer, cast and string questions

Tags:

c++

pointers

/*1*/ const char *const letter = 'A';

/*2*/ const char *const letter = "Stack Overflow";

Why is 1 invalid but 2 valid?

letter is a pointer that needs to be assigned an address. Are quoted strings addresses? I'm assuming this is why #2 is valid and that single quoted strings are not considered addresses?

Also, what is the difference between these two casting types?:

static_cast<> and ().

And lastly, if var is a char variable, why does cout << &var << come out garbled? Why must I cast it to void*?

Thanks you for your patience with beginner questions.

like image 371
ShrimpCrackers Avatar asked Aug 25 '26 07:08

ShrimpCrackers


1 Answers

Because 'A' is not a pointer, it's a char, 65 or 4116 if the underlying character set is ASCII.

"Stack", on the other hand, is string, basically the character array {'S', 't', 'a', 'c', 'k', '\0'}, which degrades to a pointer to its first character.

Your "difference between static_cast and ()" has been answered here, far better than I could.

The reason why you get rubbish with a char var = 'x'; cout << &var ... is because &var is a char * which means it's being treated as a string - in that case, cout outputs characters up to the final nul character \0 which isn't there, or is there beyond the character. The following code shows this:

#include <iostream>
int main() {
    //int q1 = 0;
    char xx = 'x';
    //int q2 = 0;
    std::cout << &xx << std::endl;
    return 0;
}

outputting:

x~Í"

When you uncomment the q lines, it works, because it's putting zeros around the character, outputting x on its own). Keep in mind this is not kosher C, it's only working because of the way my stack is organised. Don't use this is real code.

like image 101
paxdiablo Avatar answered Aug 27 '26 22:08

paxdiablo



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!