How to correctly assign a new string value?

前端 未结 3 2017
有刺的猬
有刺的猬 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:04

    The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

    strcpy(p.name, "Jane");
    

    Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

    Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

    Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

    char* firstName = "Johnnie";
    char* surname = "B. Goode";
    person p;
    
    p.name = malloc(strlen(firstName) + 1);
    p.surname = malloc(strlen(surname) + 1);
    
    p.age = 25;
    strcpy(p.name, firstName);
    strcpy(p.surname, surname);
    
    printf("Name: %s; Age: %d\n",p.name,p.age);
    
    free(p.surname);
    free(p.name);
    

提交回复
热议问题