Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top