How to correctly assign a new string value?

前端 未结 3 1976
有刺的猬
有刺的猬 2020-11-22 00:22

I\'m trying to understand how to solve this trivial problem in C, in the cleanest/safest way. Here\'s my example:

#include 

int main(int argc         


        
3条回答
  •  借酒劲吻你
    2020-11-22 01:00

    Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

    C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

    But you can call functions to help achieve what you want.

    The strncpy() function could be used here. For maximum safety I suggest following this pattern:

    strncpy(p.name, "Jane", 19);
    p.name[19] = '\0'; //add null terminator just in case
    

    Also have a look at the strncat() and memcpy() functions.

提交回复
热议问题