How do strings and char arrays work in C?

前端 未结 3 1106
抹茶落季
抹茶落季 2020-12-06 12:30

No guides I\'ve seen seem to explain this very well.

I mean, you can allocate memory for a char*, or write char[25] instead? What\'s the di

3条回答
  •  长情又很酷
    2020-12-06 13:15

    What is the difference between an allocated char* and char[25]?

    The lifetime of a malloc-ed string is not limited by the scope of its declaration. In plain language, you can return malloc-ed string from a function; you cannot do the same with char[25] allocated in the automatic storage, because its memory will be reclaimed upon return from the function.

    Can literals be manipulated?

    String literals cannot be manipulated in place, because they are allocated in read-only storage. You need to copy them into a modifiable space, such as static, automatic, or dynamic one, in order to manipulate them. This cannot be done:

    char *str = "hello";
    str[0] = 'H'; // <<== WRONG! This is undefined behavior.
    

    This will work:

    char str[] = "hello";
    str[0] = 'H'; // <<=== This is OK
    

    This works too:

    char *str = malloc(6);
    strcpy(str, "hello");
    str[0] = 'H'; // <<=== This is OK too
    

    How do you take care of null termination of string literals?

    C compiler takes care of null termination for you: all string literals have an extra character at the end, filled with \0.

提交回复
热议问题