c-无法从int值中提取字节数组值



定义了一个并集,并给定一个整数值。估计所需的阵列大小。值后面的值被定义为并集。但是,字节数组值无法打印(即,以下代码的最后一部分没有打印)。给定:

union {
unsigned int integer;
//unsigned char byte[4];
unsigned char* byte;
} foo;

在主()中

int i;
int numberOfBytes = 1;
int targetValue = 123456789;
int sum = 0;
sum = pow(16, numberOfBytes);
while (sum < targetValue) {
//printf("Trying value: %d n", (16^numberOfBytes));
numberOfBytes++;
sum += pow(16, numberOfBytes);
}
numberOfBytes++; // add 1 more byte space
printf("Number of Bytes: %d n", numberOfBytes);
printf("Sum: %d n", sum);

foo.byte = malloc(sizeof(unsigned char)*numberOfBytes);
if (foo.byte == NULL)
printf("malloc failn");
// clear foo
for (i=numberOfBytes; i >= 0;i--) {
foo.byte[i] = 0;
}
foo.integer = targetValue;
printf("Trying value: %d n", foo.integer);

以下内容未打印:

for (i=numberOfBytes; i >= 0;i--) {
printf("%x ", foo.byte[i]);
} printf("n");

在联合中,foo.byte是指向内存区域的指针。此:

foo.byte = malloc(sizeof(unsigned char)*numberOfBytes);

将foo.byte设置为指向您动态分配的内存区域的指针。然后这个:

foo.integer = targetValue;

用值覆盖该指针。

然后这个:

for (i=numberOfBytes; i >= 0;i--) {
printf("%x ", foo.byte[i]);
} printf("n");

将尝试取消引用targetValue的值,这可能会给您一个segfault。

问题是,由于您将targetValue声明为int,因此它的长度将始终为sizeof(int)字节。没有理由动态分配。

您可以将结构更改为:

union {
unsigned int integer;
unsigned char byte[sizeof(int)];
} foo;

我假设您要做的是计算出对targetValue值进行编码的最小字节数,并创建一个大小正好相同的并集。

关于并集,另一件需要理解的事情是,它们总是占用其最大成员的空间量,因此即使动态分配并集,也必须使其至少为sizeof(int)长,否则无论何时写入int,都会损坏相邻内存。

也许你需要重新思考你想做什么,并从不同的角度来看待它。

最新更新