我正在尝试编写一个函数,使用以下方式将int转换为byte:
int * key = convertTo8bits(255);
for(int i = 0; i<8; i++)
cout<<key[i]<<endl;
Run Code Online (Sandbox Code Playgroud)
这会返回意外的输出.它打印出的数组是由荒谬的大数字组成的,而这完全正常:
int * convertTo8bits(int x)
{
int total = 0;
int key[8];
for(int i = 0; i<8; i++)
key[i] = 0;
if(total + 128 <= x)
{
key[7] = 1;
total += 128;
}
if(total + 64 <= x)
{
key[6] = 1;
total += 64;
}
if(total + 32 <= x)
{
key[5] = 1;
total += 32;
}
if(total + 16 <= x)
{
key[4] = 1;
total += 16;
}
if(total + 8 <= x)
{
key[3] = 1;
total += 8;
}
if(total + 4 <= x)
{
key[2] = 1;
total += 4;
}
if(total + 2 <= x)
{
key[1] = 1;
total += 2;
}
if(total + 1 <= x)
{
key[0] = 1;
total += 1;
}
for(int i = 0; i<8; i++)
cout<<key[i]<<endl;
return key;
}
Run Code Online (Sandbox Code Playgroud)
你能说出我的错误吗?谢谢.
您正在返回指向局部变量(数组int key[8])的指针.这是未定义的行为,因为当函数完成时,局部变量超出范围(即其生命周期结束).
在C++中,您可以使用std::vector<int>而不是原始数组,因为您可以按值返回它,而不是通过指针返回.
您有许多可能的解决方案:
malloc.(这不是很好,因为你必须free在某些时候记住它.)typedef struct { int x[8]; } key;; 然后,您可以按值而不是通过指针返回结构.
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |