gpt4 book ai didi

c - 打印 union 的不同类型数组的输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:25 24 4
gpt4 key购买 nike

我创建了一个 union ,并将不同类型的数组放入其中。我按顺序打印输出,有些地方我真的不明白。

1) 为什么我的 char 数组的长度总是 8,即使内容不同?里面只有“你好”。为什么输出是“Cats rock!”当我第二次尝试打印时。我没有在数组中放置任何类似的东西。

2)又是长度问题。我所有数组的长度都是 8,甚至是并集​​的长度。为什么?

3) 我的最后一个问题是,为什么当我尝试第二次打印时,double number 的值发生了变化。

我正在向您发布我的代码并输出我得到的代码。很抱歉发了这么长的帖子,但我真的很困惑。

char: hello, 8
double: 5.557111111111111, 8
int: 1937006915 1668248096 8555, 8

char: Cats rock!
double: 0.000000000000000
int: 1937006915 1668248096 8555
size of union: 8

我的代码

#define NUM1 5.557111111111111

#define NUM2 1937006915
#define NUM3 1668248096
#define NUM4 8555
#include <stdio.h>

/*created an union*/
typedef union {
char * array1;
double num;
int * array2;
} myunion;

int main(int argc, char ** argv)
{
/* declaring union variable */
myunion uni;
/* creating my string */
char strarray[] = "hello";

/* declare an int array*/
int numarray[] = { NUM2, NUM3, NUM4 };

/* assign the string to the char pointer in the union */
uni.array1 = strarray;

/* print the union and the sizeof of the pointer */
printf("char: %s, %zu\n", uni.array1,sizeof(uni.array1));

/* assign NUM1 to the double part of union */
uni.num = NUM1;

/* print the double and its sizeof */
printf("double: %10.15f, %zu\n", uni.num, sizeof(uni.num));

/* assign array2 of union to the numarray */
uni.array2 = numarray;

/* print the values and the sizeof */
printf("int: %d %d %d, %zu\n", uni.array2[0], uni.array2[1], uni.array2[2], sizeof(uni.array2));

/* print the char array, double and int array */
printf("\nchar: %s \ndouble: %10.15f \nint: %d %d %d\n",uni.array1, uni.num, uni.array2[0], uni.array2[1], uni.array2[2]);

/* print the size of the union */
printf("size of union: %zu\n", sizeof(uni));

return 0;
}

最佳答案

sizeof(uni.array1) 在 64 位平台上始终为 8,在 32 位平台上始终为 4,因为它采用指针的大小,不知道您认为可能有多少数据在那个指针后面。数组类似。您指向数组的 C 指针是“愚蠢的”并且不理解数组有多大——您需要单独传递该信息。

这涵盖了您的问题第 1 部分和第 2 部分。我们喜欢在这里回答具体问题,所以请随时将您的第三个问题移至单独的帖子。

关于c - 打印 union 的不同类型数组的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344099/

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