我想从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