C中的联合返回类型
在以下代码中,字符串“123456789001234567890”不能完全复制到联合类型变量中。这让我很困惑C中的联合返回类型,c,C,在以下代码中,字符串“123456789001234567890”不能完全复制到联合类型变量中。这让我很困惑 #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;
#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;
}
#包括
#包括
#包括
#包括
#包括
typedef联合
{
int i;
长l;
浮动f;
双d;
无效*v;
char*s;
字符c;
}UType;
UType NewUType_s(字符*s)
{
UType temp;
strcpy(temp.s,s);//如果我们在这里打印temp.s和s,它们都是“123456789001234567890”
返回温度;
}
int main()
{
m型;
m=新类型(“123456789001234567890”);
printf(“%s\n”,m.s);
返回0;
}
结果是:1234567890123456和一些特殊字符
此问题的解决方案可能是:
- 解决方案1:对m使用
malloc()
- 解决方案2:将
样式更改为指针函数NewUType_s
一切都会正常工作UType*NewUType_s(char*s);
但是,有人知道上面提到的程序没有正确结果的原因吗?此代码的问题是,写入未初始化的指针是未定义的行为:
temp.s
没有分配一个可以复制字符串的内存块,因此strcpy
写入m您的程序不拥有的emory
修复此代码很简单:在复制之前分配内存,如下所示:
UType NewUType_s(char *s)
{
UType temp;
temp.s = malloc(strlen(s)+1);
strcpy(temp.s, s);
return temp;
}
当然,您需要释放
内存以避免内存泄漏。您正在调用的需要目标数组。UType
的值只包含一个char*
,但是(未初始化时)将指向内存中的某个随机位置。您可能需要,它将分配一个新字符串并返回指向该字符串的指针:
UType NewUType_s(const char *s)
{
UType temp;
temp.s = strdup(s);
return temp;
}
temp.s
指向哪里?temp.s
未初始化。这与联合的使用无关。这是:char*s;strcpy(s,“1234567801234567890”);
也有同样的问题。@是的,它还没有初始化。我忘记了一件小事:)为什么不使用strdup
?@hyde:strdup
是非标准的(它是由POSIX定义的,但不是由ISO C定义的).好吧!我想到了:-)@KeithThompson啊,没错。不过,如果在有它的环境中进行应用程序编程,不使用strdup不是一件好事,因为代码将依赖于库而不是纯标准C库。