如何正确分配新的字符串值? [英] How can I correctly assign a new string value?

查看:36
本文介绍了如何正确分配新的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何以最干净/最安全的方式在 C 中解决这个微不足道的问题.这是我的例子:

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

#include <stdio.h>

int main(int argc, char *argv[])
{
    typedef struct
    {
        char name[20];
        char surname[20];
        int unsigned age;
    } person;

    // Here I can pass strings as values...how does it work?
    person p = {"John", "Doe", 30};

    printf("Name: %s; Age: %d\n", p.name, p.age);

    // This works as expected...
    p.age = 25;

    //...but the same approach doesn't work with a string
    p.name = "Jane";

    printf("Name: %s; Age: %d\n", p.name, p.age);

    return 1;
}

编译器的错误是:

main.c:在函数‘main’中:main.c:18:错误:不兼容的类型时从类型分配到类型char[20]"‘字符*’

main.c: In function ‘main’: main.c:18: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’

我知道 C(不是 C++)没有 String 类型,而是使用 char 的数组,所以另一种方法是改变示例结构以保存 char 的数组代码>字符s:

I understand that C (not C++) doesn't have a String type and instead uses arrays of chars, so another way to do this was to alter the example struct to hold pointers of chars:

#include <stdio.h>

int main(int argc, char *argv[])
{
    typedef struct
    {
        char *name;
        char *surname;
        int unsigned age;
    } person;

    person p = {"John", "Doe", 30};

    printf("Name: %s; Age: %d\n", p.name, p.age);

    p.age = 25;

    p.name = "Jane";

    printf("Name: %s; Age: %d\n", p.name, p.age);

    return 1;
}

这按预期工作,但我想知道是否有更好的方法来做到这一点.

This works as expected, but I wonder if there a better way to do this.

推荐答案

第一个例子不起作用,因为你不能给数组赋值——在这方面,数组的工作(有点)像 const 指针.您可以做的是将新值复制到数组中:

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");

如果您事先知道字符串的最大大小,则可以使用字符数组,例如在第一个示例中,您 100% 确定名称将适合 19 个字符(不是 20 个,因为始终需要一个字符来存储终止零值).

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).

相反,如果您不知道字符串可能的最大大小,和/或您想优化内存使用,例如,指针会更好.避免为名称John"保留 512 个字符.但是,对于指针,您需要动态分配它们指向的缓冲区,并在不再需要时释放它,以避免内存泄漏.

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);

这篇关于如何正确分配新的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆