我有這樣的代碼。你能告訴我爲什麼它不像我預期的那樣行事嗎?爲什麼memcpy會改變字符串數組?
/*
* test.cpp
*
* Created on: Dec 6, 2012
* Author: sandeep
*/
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i=0;
string s="hello A B:bye A B";
char *input;
input=new char(s.size());
for(i=0;i<=s.size();i++)
input[i]=s[i];
char *tokenized1[2],*tokenized2[3];
tokenized1[0]=strtok(input,":");
tokenized1[1]=strtok(NULL,":");
i=0;
char *lstring;
while(i<2)
{
lstring=new char(strlen(tokenized1[i]));
memcpy(lstring,tokenized1[i],strlen(tokenized1[i])+1);
cout<<tokenized1[0]<<" "<<tokenized1[1]<<endl;
tokenized2[0]=strtok(lstring," ");
tokenized2[1]=strtok(NULL," ");
tokenized2[2]=strtok(NULL," ");
char c=tokenized2[0][0];
cout<<c<<endl;
cout<<tokenized2[0]<<" "<<tokenized2[1]<<" "<<tokenized2[2]<<endl;
i++;
}
}
並且輸出是這樣的。
hello A B by
h
hello A B
hello A B by
b
by
在第1行,第4行和第6行輸出結尾處有一些垃圾值。 爲什麼tokenized1[1]
被改變時,我做了tokenized1[0]
的記錄?以及如何解決這個問題?
2分:1)我真的不明白爲什麼這個問題被標記爲c和C++。從代碼看它幾乎是C++。 2)當使用C++時,爲什麼要使用'memcpy',手動內存管理,'strlen'等而不是'std :: copy'和'std :: string'上的操作? – Grizzly