gpt4 book ai didi

c - 以下哪个选项是在 C 中将字符串值分配给变量的最佳做法?

转载 作者:太空狗 更新时间:2023-10-29 14:49:38 24 4
gpt4 key购买 nike

我有这段 C 代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Date {
int date;
char* month;
int year;

} Date_t;

typedef Date_t* pDate_t;

void assignMonth(pDate_t birth)
{
//1)
birth->month = "Nov";

//2)
//birth->month = malloc(sizeof(char) * 4);
//birth->month = strcpy(birth->month, "Nov");

}

int main()
{
Date_t birth;
birth.date = 13;
assignMonth(&birth);
birth.year = 1969;


printf("%d %s %d\n",birth.date, birth.month, birth.year);
return 0;
}

在函数 assignMonth 中,我有两种分配月份的可能性。两者在输出中都给我相同的结果,那么它们之间有什么区别?我认为第二种变体是好的,我错了吗?如果是,为什么?如果不是,为什么?

在此先感谢您的帮助。

附言我对这两种情况下内存中发生的事情很感兴趣。

最佳答案

这取决于您以后要对 birth.month 做什么。如果您无意更改它,那么第一个更好(更快,不需要内存清理要求,并且每个 Date_t 对象共享相同的数据)。但如果是这样的话,我会将 month 的定义更改为 const char *。事实上,任何写入 *birth.month 的尝试都会导致未定义的行为。

除非您记得在 birth 超出范围之前 free(birth.month),否则第二种方法将导致内存泄漏。

关于c - 以下哪个选项是在 C 中将字符串值分配给变量的最佳做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3821112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com