2

I'm trying to write a function that converts int to byte with the following manner:

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.

2 Answers 2

8

You are returning a pointer to a local variable (the array int key[8]). This is undefined behaviour, because the local variable goes out of scope (i.e. 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.


I initially thought this was a C question, in which case my initial answer would have been appropriate:

You have a number of possible solutions:

  • Dynamically allocate the array with malloc. (This isn't great, because you'll have to remember to free it at some point.)
  • 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;; you can then return a struct by value rather than via a pointer.
Sign up to request clarification or add additional context in comments.

Comments

2

Oli has correctly identified the cause of your problem. 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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.