strcpy不适用于相同大小的数组

Nur*_*lan 1 c++ error-handling strcpy

当我尝试将一个字符串的值赋给其他使用strcpy运行时错误时.代码下方:

int main (int argc, char **argv)
{ 
  char str[5];
  char str2[5];//if set size of str2 equal to 6, no error occurs

  str[0] = 'a';
  str[1] = 'b';
  str[2] = 'c';
  str[3] = 'd';
  str[4] = 'e';

  cout<<sizeof(str)<<endl;
  cout<<str[0]<<endl;
  cout<<str[1]<<endl;
  cout<<str[2]<<endl;
  cout<<str[3]<<endl;
  cout<<str[4]<<endl;

  strcpy(str2,str);

  cout<<sizeof(str2)<<endl;
  cout<<str2[0]<<endl;
  cout<<str2[1]<<endl;
  cout<<str2[2]<<endl;
  cout<<str2[3]<<endl;
  cout<<str2[4]<<endl;

  getch();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误是:

Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted
Run Code Online (Sandbox Code Playgroud)

如果我将str2的大小设置为等于6或更多程序运行良好.这有什么问题?

Bar*_*mar 7

strcpy以零终止字符串运行.您的char数组没有终止零字节.

如果你在声明阵列时它正在工作,[6]那只是偶然的.


Gri*_*han 5

函数strcpy();期望nul \0终止字符串.str[]不是\0终止的.

因为您在代码中使用char打印数组char,所以可以使用memcpy而不是strcpy 来修正@ Karoly Horvath建议的代码.

void*memcpy(void*destination,const void*source,size_t count);

memcpy(str2, str, sizeof(str));
Run Code Online (Sandbox Code Playgroud)