char *str; str=“HELLO”; How does that work without

2019-04-12 08:11发布

Code:

    #include <stdio.h>
    int main() {
        char *str;
        char i = 'a';
        str = &i;
        str = "Hello";
        printf("%s, %c, %x, %x", str, i, str, &i);
        return 0;
    }

I get this output:

Hello, a, 403064, 28ff0b

I have following two doubts:

  1. How can I store a string without allocating any memory for it. str is a character pointer and is pointing to where char variable i. When I add str = "Hello"; aren't I using 5 bytes from that location 4 of which are not allocated?

  2. Since, I code str = &i; shouldn't str and &i have same value when I printf them? When I remove the str = "Hello"; statement str and &i are same. And if str and &i are same then I believe when I say str = "Hello" it should overwrite 'a' with 'H' and the rest 'ello\0' come into the subsequent bytes.

    I believe the whole problem is with str = "Hello" statement. It doesn't seem to be working like what I think.

Please someone explain how it works??

7条回答
\"骚年 ilove
2楼-- · 2019-04-12 08:58

The compiler writes the sequence of bytes { 'H', 'E', 'L', 'L', 'O', '\0' } in a section of the executable called the data segment.

When the application runs, it takes the address of these bytes and stores them in the variable representing 'str'.

It doesn't have to "allocate" memory in the sense that, at run time, the program does not have to ask the OS for memory to store the text.

You should try to avoid treating string literals like this as non-const. GCC's "-Wall" option promotes assignment of string literals to "char*" pointers as

warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

Many compilers, when compiling with optimization, will do something called "string pooling", which avoids duplicating strings.

const char* str1 = "hello";
const char* str2 = "hello";

If compiled with string pooling, the executable might only contain one instance of "hello".

查看更多
登录 后发表回答