在c ++中使用指针

Pum*_*kin 2 c++ pointers

我正在尝试编写一个函数,使用以下方式将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)

你能说出我的错误吗?谢谢.

Oli*_*rth 8

您正在返回指向局部变量(数组int key[8])的指针.这是未定义的行为,因为当函数完成时,局部变量超出范围(即其生命周期结束).

在C++中,您可以使用std::vector<int>而不是原始数组,因为您可以按值返回它,而不是通过指针返回.


我最初认为这是一个C问题,在这种情况下我的初步答案是合适的:

您有许多可能的解决方案:

  • 使用动态分配数组malloc.(这不是很好,因为你必须free在某些时候记住它.)
  • 将指针作为函数参数传递给数组,并将结果写入该数组.
  • 声明typedef struct { int x[8]; } key;; 然后,您可以按值而不是通过指针返回结构.