Please what wrong in this code:
#include <iostream>
#include <vector>
unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
*pChars = (char*)&container[0];
return container.size() * sizeof(int);
}
void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
int count = size / sizeof(int);
int* pIntegers = (int*)chars;
for(int i=0; i < count; ++i)
{
container.push_back(*(pIntegers++));
}
}
void Print(const std::vector<int>& container)
{
for(int i=0; i < container.size(); ++i)
{
std::cout << container[i] << std::endl;
}
}
void main()
{
std::vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
char* buffer = 0;
short bufferSize = ConvertToChars(vec1, &buffer);
std::vector<int> vec2;
ConvertToIntegers(buffer, bufferSize, vec2);
Print(vec2);
char c;
std::cin >> c;
}
function Print prints values:
- -572662307
- -842150451
- -572662307
Thank yo开发者_StackOverflow中文版u!!!
You're copying the container when you pass it to ConvertToChars
, then taking a pointer to one of its elements, then seeing the copy go out of scope, which invalidates your pointer.
I don't really understand the point of your program, but part of your problem is in your ConvertToIntegers
function, where you make your program interpret a char *
as int *
.
int* pIntegers = (int*)chars;
for(int i=0; i < count; ++i)
{
container.push_back(*(pIntegers++));
}
You're interpreting the underlying bytes as int
types, which could lead to the numbers you're seeing. I'm surprised you're not running into segmentation faults as this would cause you to overstep the block of the memory pointed to by the original char *
.
精彩评论