为什么不能在不获取int地址的情况下将inmc转换为char

为什么不能在不获取int地址的情况下将inmc转换为char

本文介绍了为什么不能在不获取int地址的情况下将inmc转换为char []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这可能是重复的,但我还没有发现其他任何有关我的确切情况的问题(还).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));您想要说:但是 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:因为 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)); 这篇关于为什么不能在不获取int地址的情况下将inmc转换为char []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-15 02:57