我是编程新手,我正在尝试反转char数组的内容。但是我似乎得到了输出中第一个元素的垃圾值。谁能告诉我我哪里做错了?
int main() {
int size = 0;
char arr[100];
cout << "Enter how many elements are added to array" << endl;
cin >> size;
cout << "Enter " << size << " elements " << endl;
for(int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Input: [ " ;
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << "]" << endl;
cout << "Output: [";
for(int j = size; j >= 0; j--)
{
cout << arr[j] << " ";
}
cout << "]" << endl;
}发布于 2020-10-07 14:59:00
问题是您正在打印一个从未初始化的元素:
for(int j = size; j >= 0; j--)
{
cout << arr[j] << " ";
}例如,如果您输入了10个值,则这些值的索引为0到9。但您访问的是元素10,该元素从未初始化,因此您将获得未定义的行为。您需要这样做:
for (int j = size - 1; j >= 0; j--)
{
cout << arr[j] << " ";
}https://stackoverflow.com/questions/64238719
复制相似问题