简体   繁体   English

在c ++中使用指针

[英]Using pointers in c++

I'm trying to write a function that converts int to byte with the following manner: 我正在尝试编写一个函数,使用以下方式将int转换为byte:

int * key = convertTo8bits(255);
for(int i = 0; i<8; i++)
cout<<key[i]<<endl;

This returns unexpected output. 这会返回意外的输出。 The array that it prints out is made of absurdly large numbers, whereas this works perfectly fine: 它打印出的数组是由荒谬的大数字组成的,而这完全正常:

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;
}

Can you point out my mistake ? 你能说出我的错误吗? Thx. 谢谢。

You are returning a pointer to a local variable (the array int key[8] ). 您正在返回一个指向局部变量的指针(数组int key[8] )。 This is undefined behaviour , because the local variable goes out of scope (ie its lifetime ends) when the function completes. 这是未定义的行为 ,因为当函数完成时,局部变量超出范围(即其生命周期结束)。

In C++, you could use a std::vector<int> instead of a raw array, because you can return it by value, rather than via a pointer. 在C ++中,您可以使用std::vector<int>而不是原始数组,因为您可以按值返回它,而不是通过指针返回。


I initially thought this was a C question, in which case my initial answer would have been appropriate: 我最初认为这是一个C问题,在这种情况下我的初步答案是合适的:

You have a number of possible solutions: 您有许多可能的解决方案:

  • Dynamically allocate the array with malloc . 使用malloc动态分配数组。 (This isn't great, because you'll have to remember to free it at some point.) (这不是很好,因为你必须记住在某些时候free它。)
  • Pass a pointer to an array in as a function argument, and write the results to that array. 将指针作为函数参数传递给数组,并将结果写入该数组。
  • Declare typedef struct { int x[8]; } key; 声明typedef struct { int x[8]; } key; typedef struct { int x[8]; } key; ; ; you can then return a struct by value rather than via a pointer. 然后,您可以按值而不是通过指针返回结构。

Oli has correctly identified the cause of your problem. Oli已正确识别问题的原因。 I think it is also worth pointing out that your code is needlessly complex. 我认为值得指出的是,你的代码是不必要的复杂。 You can write it more easily with a loop and bitwise shifting: 您可以使用循环和按位移动更轻松地编写它:

void extractbits(int x, int key[], int len)
{
    for (int i = 0; i<len; i++)
    {
        key[i] = x & 1;
        x >>= 1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM