c++ - 在这个 test() 中发生了什么意外的过程?为什么总是覆盖 ch[0 1 2...]?
问题描述
我想输入一些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::vector
对象std::string
和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';
}
}