inc*_*u26 2 c++ arrays templates copy char
这是我的代码:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
template <class T1, class T2>
void copy2(const T1 source[], T2 destination[] , int size){
for (int i=0 ; i < size ; ++i){
destination[i]=static_cast<T1>(source[i]);
}
}
int main() {
const char one[] = "hello";
char two[5];
cout << "one: " << one << endl;
cout << "two: " << two << endl;
copy2(one, two, 6);
cout << "one: " << one << endl;
cout << "two: " << two << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它输出:
一:你好
二:
一:
二:你好
而且,数组"one"是const,因此不应该改变.
PS:当我以下列方式启动数组"两个"时,它可以工作(但是为什么?):
char two[8];
Run Code Online (Sandbox Code Playgroud)
但是,当我以下列两种方式启动它时,我会遇到奇怪的错误:
char two[6];
Run Code Online (Sandbox Code Playgroud)
要么
char two[7];
Run Code Online (Sandbox Code Playgroud)
我最好的猜测是,two
并且one
彼此相邻的堆栈如下:
t w o - - o n e - - -
--------------------------------------------
| | | | | | h | e | l | l | o | \0 |
--------------------------------------------
Run Code Online (Sandbox Code Playgroud)
因为你two
通过将大小6传递到大小为5的copy2
时候溢出缓冲区two
,所以内存最终会像这样:
t w o - - o n e - - -
--------------------------------------------
| h | e | l | l | o | \0 | e | l | l | o | \0 |
--------------------------------------------
Run Code Online (Sandbox Code Playgroud)
这就是为什么two
似乎持有"你好"而one
没有显示任何东西(因为两个超过它的缓冲区,现在空终止符是第一个字符one
).