1

I have the below code where a vector<int> which contains bytes is converted to a char[]. This char[] is then output.

vector<int> data;
data.push_back(33);
data.push_back(69);
data.push_back(80);
data.push_back(0);
data.push_back(0);
data.push_back(74);
data.push_back(255);

char* result = new char[data.size()];

for(int i = 0; i < data.size(); i++) {
  result[i] = (char)data[i];
  cout << i << " = " << (char)data[i] << endl;
}

cout << "--" << endl;

for(int i = 0; i < sizeof(result); i++) {
  cout << i << " = " << result[i] << endl;
}

This code produces the following output.

0 = !
1 = E
2 = P
3 = 
4 = 
5 = J
6 = �
--
0 = !
1 = E
2 = P
3 = 

However, I expected it to be

0 = !
1 = E
2 = P
3 = 
4 = 
5 = J
6 = �
--
0 = !
1 = E
2 = P
3 = 
4 = 
5 = J
6 = �

I suspect this has something to do with sizing, but I am not certain.

What is going wrong with the code?

1
  • 1
    sizeof(result) will be 4 (or 8 in x64), since that's the size of a pointer. Commented Nov 22, 2013 at 19:34

2 Answers 2

5

The way you're using sizeof() is incorrect. It's returning the size of the pointer, not the size of the pointed-to thing. There is no way to access the size of the pointed-to thing given just its pointer when you're pointing to an array of items.

You'll have to remember the size you allocated with new somewhere and use that.

Sign up to request clarification or add additional context in comments.

Comments

0
for(int i = 0; i < sizeof(result); i++)  // PROBLEM!
{
  cout << i << " = " << result[i] << endl;
}

result is a pointer and it appears you are on a 32-bit system, so sizeof(result) is 4 (bytes). So your loop is iterating from [0, 4). You need to pass the size, or use the vector's size:

for(int i = 0; i < data.size(); i++) 
{
  cout << i << " = " << result[i] << endl;
}

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.