- 论坛徽章:
- 0
|
程序:
第一种情况:
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- typedef struct
- {
- char *data;
- }Buf;
- int main()
- {
- Buf myBuf;
- char str[] = "C++ is a case-sensitive, freeform programming language. This chapter pre sents the lexical rules for the language.";
- myBuf.data = new char[strlen(str)];
-
- memcpy(myBuf.data, str, strlen(str));
-
- cout<<"myBuf.data = "<< myBuf.data<<endl;
- cin.get();
- return 0;
- }
复制代码
输出结果:
myBuf.data = C++ is a case-sensitive, freeform programming language. This chapte
r presents the lexical rules for the language.??
第二种情况:
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- typedef struct
- {
- char *data;
- }Buf;
- void allocMem(Buf &buf, const char *str)
- {
- buf.data = new char[sizeof(str)];
- memcpy(buf.data, str, sizeof(str));
- }
- int main()
- {
- Buf myBuf;
- char str[] = "C++ is a case-sensitive, freeform programming language. This chapter presents the lexical rules for the language.";
- allocMem(myBuf, str);
- cout<<"myBuf.data = "<< myBuf.data<<endl;
- cin.get();
- return 0;
- }
复制代码
输出结果:
myBuf.data = C++ ??1
请高手指点,什么原因导致了这种错误;如何得到想要的结果。
3ks!
[ 本帖最后由 JustUSTC 于 2006-12-28 11:04 编辑 ] |
|