Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.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

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_Types - Fatal编程技术网

C 在字符数组中存储整数

C 在字符数组中存储整数,c,arrays,types,C,Arrays,Types,我一直在读这篇文章 我需要将int存储在字符数组中 因此,我阅读了前面的帖子,并尝试制作自己的演示。但它不起作用,试图弄明白为什么在很长一段时间内不起作用。也许你能给我一些线索或想法 #include <stdio.h> int main(void) { char buffer[4]; int y = 2200; buffer[0] = (y >> 0) & 0xff; buffer[1] = (y >> 8) &a

我一直在读这篇文章

我需要将int存储在字符数组中

因此,我阅读了前面的帖子,并尝试制作自己的演示。但它不起作用,试图弄明白为什么在很长一段时间内不起作用。也许你能给我一些线索或想法

#include <stdio.h>

int main(void) {

    char buffer[4];
    int y = 2200;
    buffer[0] = (y >> 0) & 0xff;
    buffer[1] = (y >> 8) & 0xff;
    buffer[2] = (y >> 16) & 0xff;
    buffer[3] = (y >> 24) & 0xff;

    int x = buffer[0];

    printf("%i = %i\n", y, x);
}

x=buffer[0]
不能满足您的要求。尝试
memcpy(&x,buffer,sizeof(x))
。(您需要添加
#include

x=buffer[0]
无法实现您的愿望。尝试
memcpy(&x,buffer,sizeof(x))
。(您需要添加
#包括

缓冲区[0]
处的
字符的值隐式转换为int,复制到
x
。它不会将从
缓冲区开始的
int
字节的第一个
大小解释为
int
,这正是您想要的(想想这种行为在常见场景中会微妙地破坏的邪恶方式,即
char c=10;int x=c
.Oops!)

要知道,
buffer[n]
不会返回内存地址,而是返回一个
char
。要将
sizeof int
元素解释为一个整体
int
只需将
buffer
转换为
int*

int x = *((int*)buffer);
对于偏移量
n
(以
int
s测量,而不是
char
s测量):


还请注意,您的代码假定
sizeof int==4
,这是不保证的

缓冲区[0]
处的
字符的值隐式转换为int,复制到
x
。它不会将从
缓冲区开始的
int
字节的第一个
大小解释为
int
,这正是您想要的(想想这种行为在常见场景中会微妙地破坏的邪恶方式,即
char c=10;int x=c
.Oops!)

要知道,
buffer[n]
不会返回内存地址,而是返回一个
char
。要将
sizeof int
元素解释为一个整体
int
只需将
buffer
转换为
int*

int x = *((int*)buffer);
对于偏移量
n
(以
int
s测量,而不是
char
s测量):



还请注意,您的代码假定
sizeof int==4
,这是不保证的。

这并不能直接解决您的问题,但请注意您对系统上
int
的大小所做的假设。这并不能直接解决您的问题,但是请注意您对系统上
int
的大小所做的假设。
int x = *((int*)buffer);
int x = *((int*)buffer + n);