【问题标题】:C++ Dynamic array of char arrayschar数组的C++动态数组
【发布时间】:2016-10-25 21:43:15
【问题描述】:

我正在尝试制作 char 数组的动态数组

const int nameLength = 10;
int dataCount = 5;

// Initialize array of char array
char ** name;
name = new char*[dataCount];
for (int i = 0; i < dataCount; i++)
    name[i] = new char[nameLength];

// Prompt for names
for (int i = 0; i < dataCount; i++) {
    char userInput[nameLength];
    cout << "Input data " << i << " :";
    cin >> userInput;
    name[i] = userInput;
}
cout << endl;

// Display data entered
for (int i = 0; i < dataCount; i++) {
    cout << "Name" << i << " : " << name[i] << endl;
}

但是输出错误:

Input data 0 :abcde
Input data 1 :fghij
Input data 2 :klmno
Input data 3 :pqrst
Input data 4 :uvwxy

Name0 : uvwxy
Name1 : uvwxy
Name2 : uvwxy
Name3 : uvwxy
Name4 : uvwxy

如果我将输入部分更改为此,它将按预期工作:

    cin >> name[i];

但在我的情况下,我不能直接将数据输入到变量中。
谁能解释代码有什么问题?我到处搜索,但似乎没有帮助

【问题讨论】:

  • 然后使用strcpy。或者更好std::vector&lt;std::string&gt;。为什么不能用最后的代码sn-p?
  • 优先使用std::string,而不是 C 风格的字符数组。更喜欢使用std::vector 而不是动态分配的数组。
  • 实际上char数组在一个类中,我需要一个函数来输入char数组

标签: c++ arrays pointers char


【解决方案1】:

您只是在复制指针,而不是字符串。所以事实上你所有的name[i]都等于userInput,记住它们都是指针。如果你想复制完整的字符串,你应该使用 strcpy 例如。

由于您要复制指针,它们都指向同一个字符串并显示您最后输入的内容。

【讨论】:

  • 有没有办法在没有STL的情况下复制它?
  • 如果您愿意,可以手动复制。类似于for(int j = 0; j &lt; nameLength; ++j) name[i][j] = userInput[j]
  • 顺便说一句,strcpy不一定在STL中,它只是一个C函数。
  • strcpy 就像我需要的一样工作。起初我认为我需要将我所有的 char 数组更改为字符串才能使用它。谢谢!
猜你喜欢
  • 2016-04-07
  • 2015-01-11
  • 1970-01-01
  • 2014-06-03
  • 2012-01-09
  • 2020-11-11
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
相关资源
最近更新 更多