【问题标题】:strcpy_s for char** and char[][]strcpy_s 用于 char** 和 char[][]
【发布时间】:2012-06-07 19:26:51
【问题描述】:

我使用strcpy_s如下:

char names[2][20];
strcpy_s(names[0],"Michael");
strcpy_s(names[1],"Danny");

而且一切正常。

但是当我换成char **时,

int size1=2;
int size2=20;

char **names=new char*[size1];
for(int i=0;i<size1;i++)
  names[i]=new char[size2];
strcpy_s(names[0],"Michael");
strcpy_s(names[1],"Danny");

它给了我这个错误信息:

错误 C2660: 'strcpy_s' : 函数不接受 2 个参数

为什么会这样?我需要动态创建char数组,怎么办?

【问题讨论】:

  • strcpy != strcpy_s。你的意思是用哪一个?
  • 因为这是 C++,请考虑使用 std::vector&lt;std::string&gt;
  • @hmjd 不要考虑使用它。使用它。
  • @user1203803 清晰!

标签: c++ arrays char strcpy


【解决方案1】:

strcpy_s 有两种形式(至少在 Windows 上):一种用于指针,另一种用于数组。

errno_t strcpy_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource 
);
template <size_t size>
errno_t strcpy_s(
   char (&strDestination)[size],
   const char *strSource 
); // C++ only

使用指针时,您必须指定目标缓冲区的元素数量:

strcpy_s(names[0], size2, "Michael");
strcpy_s(names[1], size2, "Danny");

【讨论】:

  • +1 不知道模板版本(即使它在我删除的答案中链接的页面上!)
  • @Michael 没问题。不要忘记单击绿色复选标记以接受正确的答案。
猜你喜欢
  • 2020-04-27
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多