此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?

What unexpected process happened in this test()?why Always overwrite ch[0 1 2...]?

本文关键字:ch 覆盖 为什么 发生了 什么 过程 意外 测试      更新时间:2023-10-16

我想输入一些char[100],然后将它们存储在char *ch[100]中,但失败了。

ch[0,1,...last]test()中是正常的.

但是ch[0...last]==ch[last]退出test().

发生了什么事?

#include<iostream>
#include<cstring>
using namespace std;
char *ch[100];
int N=0;
int test(char *strValue)
{
ch[N++]=strValue;//normal in test() when debug 
return 0;
}
int main()
{
int n;
char str[100];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>str;
test(str);
}
cout<<"N:"<<N<<endl;
for(int i=0;i<N;i++)
{
cout<<ch[i]<<endl;//abnomal!!! ch[0...N-1] become ch[N-1],what happened?
}
return 0;
}

语句

ch[N++]=strValue;

复制指针而不是字符串。

这意味着ch的所有元素都将指向同一个字符串,该字符串将仅包含最后一个输入的内容。

自然C++解决方案是使用std::string对象的std::vector,并根据需要push_back新字符串:

#include <iostream>
#include <vector>
#include <string>
int test(std::vector<std::string>& ch, std::string const& str)
{
ch.push_back(str);
}
int main()
{
// Container for all our strings
std::vector<std::string> strings;
// The number of strings to read
size_t number_of_strings;
std::cin >> number_of_strings;
// Create space for the strings (slight optimization)
strings.reserve(number_of_strings);
// Read the strings
for (size_t i = 0; i < number_of_strings; ++i)
{
std::string str;
std::cin >> str;
test(strings, str);  // Will add the string to the vector
}
// Print the number of strings we've read
std::cout << "N:" << strings.size() << 'n';
// Lastly display all strings
for (auto const& str : strings)
{
std::cout << str << 'n';
}
}