我有下面的代碼,其中包含字節的vector<int>
被轉換爲char[]
。然後輸出char[]
。C++轉換字節
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;
}
此代碼產生以下輸出。
0 = !
1 = E
2 = P
3 =
4 =
5 = J
6 = �
--
0 = !
1 = E
2 = P
3 =
不過,我希望它是
0 = !
1 = E
2 = P
3 =
4 =
5 = J
6 = �
--
0 = !
1 = E
2 = P
3 =
4 =
5 = J
6 = �
我懷疑這是與大小,但我不能肯定。
代碼出了什麼問題?
'sizeof(result)'將爲4(或x64中的8),因爲這是指針的大小。 –