为什么不能在不获取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 ofn
intos
".
但是 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 inn
intos
."
因为 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 ofn
intos
".