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

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

问题描述

我想了解如何解决这个小问题在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 works?
    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;
}

编译器的错误是:

The compiler's error is:

main.c中:在函数'主':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 ++)没有字符串类型,而是使用字符数组,所以另一种方式来做到这一点是改变的例子结构持有字符的指针:

I understand that C (not C++) has no 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. Thanks.

推荐答案

第一个例子不工作,因为你不能将值分配给阵列 - 阵列工作(有点)像在这方面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).

相反,指针是更好,如果你不知道你的字符串可能的最大尺寸,和/或要优化内存使用情况,例如避免保留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天全站免登陆