Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 字节数组中下一个字节的大小_C_Arrays_Byte - Fatal编程技术网

C 字节数组中下一个字节的大小

C 字节数组中下一个字节的大小,c,arrays,byte,C,Arrays,Byte,我有一个无符号字符,我向其中添加整数,但我想得到下一个字节的sizeof(即sizeofunsigned short int或unsigned int等等) 以下代码演示了我想要的内容: #include <stdio.h> static void write_ushort(unsigned char *b, unsigned short int value) { b[1] = value >> 8; b[0] = value; } static void write_

我有一个无符号字符,我向其中添加整数,但我想得到下一个字节的
sizeof
(即
sizeof
unsigned short int
unsigned int
等等)

以下代码演示了我想要的内容:

#include <stdio.h>

static void write_ushort(unsigned char *b, unsigned short int value) { b[1] = value >> 8; b[0] = value; }
static void write_ulong(unsigned char *b, unsigned long int value) { write_ushort(b + 2, value >> 16); write_ushort(b, value); }

static unsigned short int read_ushort(const unsigned char *b) { return b[1] << 8 | b[0]; }
static unsigned long int read_ulong(const unsigned char *b) { return read_ushort(b + 2) <<16 | read_ushort(b); }

int main() {
     unsigned char b[2];
     unsigned int v0;       /* 4 */
     unsigned short int v1; /* 2 */

     v0 = 200; v1 = 1235;
     write_ushort(&b[0], v0); write_ulong(&b[1], v1);

     /* what i expect printf to output is:
      * 4 2 
      * but it obviously outputs 1 1 */
     printf("%d %d\n", read_ushort(&b[0]), read_ulong(&b[1]));
     printf("%d %d\n", (int)sizeof(b[0]), (int)sizeof(b[1]));
     return 0;
}
#包括
静态void write_ushort(无符号字符*b,无符号短int值){b[1]=value>>8;b[0]=value;}
静态void write_ulong(无符号字符*b,无符号长整型值){write_ushort(b+2,值>>16);write_ushort(b,值);}

static unsigned short int read_ushort(const unsigned char*b){return b[1]C是静态类型的,您不能仅仅通过为变量(或数组)赋值来更改其数据类型。事实上,您根本无法更改变量的数据类型:变量对应(几乎完全对应)在编译时定义大小的特定内存块。您可以强制转换变量,以便将它们视为特定操作的不同类型,但内存块的大小始终相同



而且,由于变量只是一块内存,计算机(或编译器)无法知道您使用的是
char[2]
数组来存储
短的
长的
。你必须自己跟踪这一点。

这是不可能的。
sizeof
操作符将返回类型的大小,或声明的变量类型的大小。你不能从中提取任何其他内容,你的代码也不会跟踪变量的类型在将编号分配给新变量之前,已将其存储在中

无论
v0
v1
的类型如何,当它们存储在数组的元素中时,都会转换为
无符号字符


如果希望将
4 2
作为输出,则需要将
sizeof(v0)
sizeof(v1)
传递到
printf
,或者以其他方式跟踪此情况。

这里有一个主要问题:

write_ulong(&b[1], v1);

取第二个字节(双字节数组)然后将其传递到
write_uulong
中,在那里它作为四个字节的数组处理。这意味着您在原始数组
b
之外写入了几个字节,并覆盖了堆栈。这是未定义的行为,会使您的程序表现得非常奇怪。

旁注:256和512都不能放入
无符号字符中>@Mysticial噢,是的,你说得对……我会更新这个问题。谢谢你
b[0]
b[1]
都是
无符号字符
…当你分配给它们时,右值(
v0
v1
)会被视为
无符号字符
。你的问题看起来仍然像是
sizeof(b[0]/code>和
sizeof>(b[1])
以某种方式改变。它们不会改变。
sizeof(无论什么)
是一个编译时常量,因此与任何变量的值无关(并且
sizeof(b[0])
sizeof(b[1])
无论如何都是相同的)。