向后打印列表
Printing list backwards
我有一个问题,这个程序是向前和向后打印出一个列表,但是当我向后打印出列表时,列表中的第一个数字是一个随机的大量数字,而不是正确的数字。例如
0 1 2 3 4 5 6 7 8 0
4286398 8 7 6 5 4 3 2 1 0
谁能解释一下我的代码有什么问题?
还有谁能告诉我如何将计数器从printList函数传递给一个名为checkList()的新函数,以便计数器在checkList()中具有与printList()结束时相同的值。
代码:void printList(int array1[]){
int counter = 0;
int x;
ifstream theFile("list.txt");
while(theFile >> x){
array1[x] = x;
cout << array1[x] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
int n = counter;
for(int i = n -1; i >= 0; i--){
cout << array1[i] << " ";
}
这是罪魁祸首:
array1[x] = x;
如果你的数组输入值是0 1 2 3 4 5 6 7 8 0
,那么在循环的最后一次迭代中,你正在做array1[0] = 0
。重写数组中的第一项,同时增加计数器。然后,当你反转它array[9]
包含垃圾值,因为你从来没有设置它。
您有一个问题,因为行array1[x]=x;
。如果你的文件中的数字是0,你的代码实际上会工作。9,但最后的数字是另一个0,所以你不设置array1[9]为任何值
你应该有一些变量来索引数组,比如:
int counter = 0;
while(theFile >> x){
array1[counter] = x;
cout << array1[counter] << " ";
counter = counter + 1;
}
你在做什么
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
array1[4] = 4;
array1[5] = 5;
array1[6] = 6;
array1[7] = 7;
array1[8] = 8;
array1[0] = 0; // here
array1[9]未初始化
代码中有一些严重的问题:
ifstream theFile("list.txt");
while(theFile >> x){
array1[x] = x;//^^this is evil
cout << array1[x] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
//^^extra colon, though not wrong here but not good practice
从文件中读取并填充数组,在您的特殊情况下,您有:
0 1 2 3 4 5 6 7 8 0
你有10个元素,但是你的array1
最终会变成9
,因为最后一次读的是0
,而array1[0]
又被写成了0
。因此,当您输出array1
时,您将永远不会得到10
数字,因为您的数组实际上存储了9个数字。这就是为什么你看到垃圾值,如果你试图访问array1[9]
,这个值没有被填满,一些垃圾原始内存值。
相反,您可以尝试这样做:
int counter = 0;
int x;
ifstream theFile("list.txt");
while(theFile >> x){
array1[counter] = x;
cout << array1[counter] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
你向上计数错误,最终击中未初始化的内存后,你的数组。你应该把数组的长度作为参数传递给函数。
当数组衰减为指针时,您将无法恢复其长度。
void printList(int array1[], into size){ }
那你就不用这么复杂地计算它的长度了
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 直接 2D 呈现到命令列表和打印:图片压缩
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 只有我的"链接列表"中的第一个节点正在打印
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- C++使用相反的顺序打印带有逗号的列表
- 如何实现否定用户输入退出程序和打印列表?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- C++:一种在列表中打印所有对的优雅方式
- C 打印集合列表
- 如何打印简单的链接列表(C )
- 如何编写循环以通过列表迭代并打印列表中每个元素的数据的数据
- 使用for_each从对象列表中调用打印功能
- 我的链接列表打印功能进入无限循环
- 链接列表打印null -C
- 链接列表打印不起作用.
- 将整数列表打印为逗号分隔的数字列表,每行最多 10 个
- 奇怪的列表打印函数行为。如果我打印"n"则有效,如果我删除它则不起作用