此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
What unexpected process happened in this test()?why Always overwrite 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::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';
}
}
相关文章:
- 使用ios:ate写入到流会覆盖现有文件
- 我可以重新分配/覆盖std::字符串吗
- 叮叮当当在修复时插入多个"覆盖"说明符
- 谷歌模拟和覆盖关键字
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 使用子类覆盖基类中定义的函数
- 当覆盖存在时调用基本虚拟"binded to object"函数
- C++指针在 for 循环中被覆盖
- "main"函数堆栈中的对象在第一个任务运行时被覆盖 (FreeRTOS)
- 为什么我的全局 new() 覆盖被绕过了?
- 被覆盖的函数不会反映在基类中,这是正常行为吗?
- C++找出覆盖同一行的数组
- 专门化模板覆盖函数/避免对象切片
- 重写打印函数而不是覆盖基类
- C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误
- 如何在 c++ 中覆盖相同的文本文件
- 覆盖应用程序的低级别键盘挂钩问题
- glBindTexture 是否覆盖活动纹理单元的内容
- "虚拟""覆盖"析构函数