我在嵌入式C环境中有以下代码,Compiler:Hightec(Big-Endian)
unsigned char GlobalVar;
Func_A()
{
unsigned char var1,Retval;
var1 = 0;
retval = Func_B(0,&var1);
}
unsigned char Func_B (unsigned char val, void* ptr )
{
unsigned long localvar;
localvar = (unsigned long)GlobalVar;
*(unsigned char*)ptr = (unsigned char)localvar;
return (0);
}
输入: GlobalVar = 1, Func_A调用Func_B。
预期输出 Func_B被调用, 第二个参数更新为值1。
我看到的内容: Func_B被调用, 第二个参数保持值64(0100 0000)。
其他评论
1. Func_A is an application file.
2. Func_B is part of a different software module.
3. Func_A reads the value from Func_B to do some action in application.
4. Func_B reads the value from a global variable (it is an array) and copies it into the second argument passed to it.
5. The second argument is a void* because Func_B can read different global variables and finally it would typecast based on parameter 1
(this part is not related, so i have excluded the related code)
您认为这里发生了什么?
EDITED
重新编辑
对不起,我匆忙关闭了这个问题
我在这里面临的问题
我是如何解决的
我怀疑
你有什么专家的想法?我真的想知道这种行为的根本原因是什么?
答案 0 :(得分:0)
无符号长整数为4字节,无符号字符长度为1字节。您将1字节值分配给4字节值,并再次将该4字节值分配给1字节值。在无符号长变量的剩余3个字节中可能存在垃圾值,并且可能会(根据字节顺序)将其分配给unsigned char变量。
答案 1 :(得分:0)
你看到了什么:Func_B is called, Second parameter holds value 64 (0100 0000).
unsigned char Func_B (unsigned char val, void* ptr )
{
unsigned long localvar;
printf("val = %d\n", *(unsigned char*)ptr);
/*HERE : val = 0*/
localvar = (unsigned long)GlobalVar;
*(unsigned char*)ptr = (unsigned char)localvar;
return (0);
}
我看到:从上面的函数中,第二个参数是void *ptr
。当我尝试打印它的内容时,值是预期的。 val = 0
。
@DarkKnight:How did you check the value of the second parameter ?