gpt4 book ai didi

c - C 中的 Union 返回类型

转载 作者:行者123 更新时间:2023-12-02 07:34:06 24 4
gpt4 key购买 nike

在下面的代码中,字符串“12345678901234567890”无法完整复制到 union 型变量中。这让我真的很困惑?

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

typedef union
{
int i;
long l;
float f;
double d;
void *v;
char *s;
char c;
} UType;

UType NewUType_s(char *s)
{
UType temp;
strcpy(temp.s, s); // If we print temp.s and s here, both of them are "12345678901234567890
return temp;
}

int main()
{
UType m;
m = NewUType_s("12345678901234567890");
printf("%s\n", m.s);

return 0;
}

结果是:1234567890123456和一些特殊字符?

这个问题的解决方案可能是:

  • 方案一:对m使用malloc();

  • 解决方案 2:将 NewUType_s 样式更改为指针函数 UType *NewUType_s(char *s); 一切都会正常运行,

但是,有人知道上述程序没有正确结果的原因吗?

最佳答案

此代码的问题在于写入未初始化的指针是未定义的行为:temp.s 尚未分配可将字符串复制到其中的内存块,因此strcpy 写入您的程序不拥有的内存。

修复此代码很简单:在复制之前分配内存,如下所示:

UType NewUType_s(char *s)
{
UType temp;
temp.s = malloc(strlen(s)+1);
strcpy(temp.s, s);
return temp;
}

当然你需要释放内存以避免内存泄漏。

关于c - C 中的 Union 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579224/

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