문제

i tried the following:

int main()
{
    char* a = "sdwgfwegwe wefwef wefwefwefwysadqaw";
    char* b = "acd";
    char* c = "sdwgfwegwe wefwef wefwefwefwysadqaw";
    char* d;

    d = "acd";

    printf("%p\n", a);
    printf("%p\n", b);
    printf("%p\n", c);
    printf("%p\n", d);

    getchar();

    return 0;
}

and on the output(console) a and c had the same address as well as b and d. i thought about implementing a lookup-table for every character. is there any benefit/situation of doing it? and what does the compiler makes out of it (the example above, not the lookup-table :) )? check if this string is already used, if not, reserve memory for the given string -> return it to a? has anybody some book tips or links, that go this deep and explain the internal memory allocations/management, even if it is compiler dependent? thanks in advance.

도움이 되었습니까?

해결책

String literals are specified to be unmodifiable in C.

And from the C99 rationale document:

"This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and to perform certain optimizations"

다른 팁

The C++ answer (§2.14.5):

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined.

It is entirely up to the implementation how it decides to create the string literal objects. One implementation may do it differently to another. Yours appears to treat identical string literals as the same object.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top