use*_*627 3 c++ arrays pointers
我正在学习使用指针来复制char数组.
我在C++中有以下代码.我想要做的是使用指向另一个指针数组(temp)的传输和数组(set1).
但是当我尝试打印(temp)时,它与(set1)不同.
通过指针将数组传输到另一个临时数组指针.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char set1[] = "ABC";
char* p = &set1[0];
int tempSize = 0;
char* temp = new char[256];
for (int i = 0; i < 3; i++)
{
*temp = *p;
cout << *temp; // ABC
++temp;
++tempSize;
++p;
}
cout << "\n";
for (int i = 0; i < tempSize; i++)
{
cout << temp[i]; // Why ABC is not printed?
}
delete [] temp;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
//为什么不打印ABC?
因为您的指针在未定义的行为区域中行进:
char* temp = new char[256];
...
++temp; // gone !!
Run Code Online (Sandbox Code Playgroud)
最重要的是,
\0在最后终止字符串(可能在你的代码中不需要)delete[]最后这个腐败的指针.由于您是为了学习目的而写作,我建议您对代码进行简单的修复:
char* const temp = new char[256];
^^^^^ ensures `temp` is not modifiable
Run Code Online (Sandbox Code Playgroud)
现在temp[i]用于遍历目的.