次のコードでは、文字列 "12345678901234567890" を共用体型の変数に完全にコピーすることはできません。これは私を本当に混乱させますか?
#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 といくつかの特殊文字?
この問題の解決策は次のとおりです。
解決策 1:
malloc()
m に使用します。解決策 2:
NewUType_s
スタイルをポインター関数に変更するUType *NewUType_s(char *s);
と、すべてが正常に機能します。
しかし、上記のプログラムが正しい結果をもたらさない理由を誰かが知っていますか?