简体   繁体   中英

What happens when I assign a string to a char?

I wrote:

char ch = "ABC";

Now, when I compiled it, I'm not getting any error. But, if I try to display these characters individually or the entire String all at once I can't do that because whenever I try to do so, my program crashes.

What's happening in this program?

What should normally happen (at least with a reasonably modern compiler) is that you get an error message, because the conversion involved shouldn't happen without an explicit cast.

But, let's consider what happens when/if we do force the compiler to do the dirty deed, so to speak. Let's consider a program that includes a cast to force the conversion and does a couple of other things that will make what's really happening a lot more clear (I think).

#include <stdio.h>

int main() {
    char const *s = "ABC";

    int i = (int)s;
    unsigned char c = (unsigned char)s; 

    printf("%p\n%8x\n%8x\n", s, i, c);
}

(I've used unsigned char instead of char simply to prevent the value from being sign-extended if bit-7 of the pointer happens to be set).

The output I get from this looks like this:

0x4005f4
  4005f4
      f4

So what's happening here is that "ABC" is a string literal, which we can use to initialize (among other possibilities) a pointer to (const) char. If we convert that to a pointer to void, we can see the address at which that string literal is being stored (note: if you compile this, the address you get is likely to be different).

If we convert that address to an unsigned int, we get the same value. This isn't guaranteed by the standard, but it's pretty much what you're likely to see in most typical cases.

Finally, we convert the pointer to a char . Printing that out in hexadecimal, we can easily see that it's just retaining the 8 least significant bits of the address. Again, the fact that it's exactly 8 bits isn't guaranteed by the standard, but it's a pretty typical size for char .

Disclaimer: although you can probably expect to see results similar to what I've shown, nearly none of this is guaranteed. Printing out a pointer to void is supported, but the exact format that will be used is up to the compiler/library. Likewise, the result of converting to an integer type isn't entirely guaranteed--but on most typical computers/compiler implementations, you can expect to see results similar to what I've shown above.

Bottom line: the value assigned to the char is typically going to be the least significant 8 bits of the address assigned for storing the string literal (which is essentially useless).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM