我想從charArray
做一個memcpy()
到一個整數變量。複製完成,但在嘗試打印複製的值時,某些垃圾正在打印。按照我的代碼。從一個字符數組到一個整數的C++ memcpy
是否有任何問題與填充?
#include <iostream>
#include "string.h"
using namespace std;
int main()
{
char *tempChar;
string inputString;
int tempInt = 3;
cout << "enter an integer number" << endl;
cin >> inputString;
tempChar = new char[strlen(inputString.c_str())];
strcpy(tempChar, inputString.c_str());
memcpy(&tempInt, tempChar, sizeof(int));
cout << endl;
cout << "tempChar:" << tempChar << endl;
cout << "tempInt:" << tempInt << endl;
return 0;
}
你怎麼知道來自 「非垃圾」 的 「垃圾」?你打印什麼錯誤?你期望在印刷的價值中看到什麼? – AnT
你真的認爲int的內存表示就像'133742'嗎? o.O – 2012-12-26 08:13:53