为什么不能在不获取int地址的情况下将inmc转换为char []? [英] Why can't I memcpy an int to a char[] without getting the address of the int?

查看:45
本文介绍了为什么不能在不获取int地址的情况下将inmc转换为char []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是重复的,但我还没有发现其他任何有关我的确切情况的问题(还).

This might be a duplicate, but I haven't found any other question dealing with my exact situation (yet).

这就是我想要做的:

int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)n, sizeof(n));
printf("%d", s);

基本上,我想将 n 复制到 s 中,而不必获取 n 的地址.当我运行它时,它给我一个分割错误.但是,这可行:

Basically, I want to copy n into s without having to get the address of n. When I run this, it gives me a segmentation fault. This, however, works:

printf("%d", (char *)n);

所以我知道问题出在memcpy调用中.为什么我不能像这样将int存入char []中?

So I know that the problem is in the memcpy call. Why can't I memcpy an int into a char[] like this?

推荐答案

您会遇到分段错误,因为您尝试执行的操作不是代码所声明的.

You get a segmentation fault because what you're trying to do is not what your code states.

int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)n, sizeof(n));

想要说:

将表示 n 值的 sizeof(int)个字节复制到 s 中."

"copy the sizeof(int) bytes representing the value of n into s".

但是 memcpy()是关于复制内存对象而不是值的.对象驻留在给定地址,并且包含一个给定值.以 n 给出值,以& n 给出地址.

But memcpy() is about copying memory objects, not values. An object resides at a given address, and contains a given value. Taking n gives the value, taking &n gives the address.

然后构造(char *)n 告诉编译器将 n 解释为地址> ,所以您说的是:

And the construct (char *)n tells the compiler to interpret the value of n as the address of a char, so what you are saying is:

sizeof(int)个字节复制到 s 中的 n 中的地址处."

"copy the sizeof(int) bytes at the address contained in n into s."

因为 n = 12 ,所以您正在从地址 0x00000012 中读取...这很可能不是从中读取的合法地址(因此出现段错误).

Since n = 12, you are reading from address 0x00000012... which is most likely not a legal address to read from (hence the segfault).

通过在将那个(而不是 value )转换为 char * 之前,先获取 n 的地址,您的陈述符合您的意图:

By taking the address of n before casting that (instead of the value) into char *, your statement matches your intent:

int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)&n, sizeof(n));

将位于 n 地址的 sizeof(int)个字节复制到 s 中."

"copy the sizeof(int) bytes at the address of n into s".

这篇关于为什么不能在不获取int地址的情况下将inmc转换为char []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆