[英]Unexpected Output in C++ while printing newline character
Anyone knows why it happens when I print a newline after printing out marks then the output is unexpected.任何人都知道为什么在打印出标记后打印换行符时会发生这种情况,然后输出是意外的。 When I remove it, the program works fine and gives an expected apart from a newline.
当我删除它时,程序运行良好,除了换行符外,还给出了预期的结果。
#include <iostream>
using namespace std;
int sum(int[], int);
int max(int*, int);
int main()
{
int marks[5] = { 1, 2, 3, 4, 5 };
cout << marks << "\n";
cout << sum(marks, 5) << "\n";
cout << max(marks, 5) << "\n";
return 0;
}
int sum(int arr[], int n)
{
cout << arr << "\n";
int total = 0;
for (int i; i < n; i++) {
total += arr[i];
}
return total;
}
int max(int* ptr, int n)
{
cout << ptr << "\n";
int max = 0;
for (int i = 0; i < n; i++) {
max = max > *(ptr + i) ? max : *(ptr + i);
}
return max;
}
Output when the newline is printed.打印换行符时输出。
Output when the newline printing statement is removed.删除换行打印语句时的输出。
In your sum()
function's for loop, variable i
is not initialized, which means its value is not predictable.在
sum()
函数的 for 循环中,变量i
未初始化,这意味着其值不可预测。 Via gdb
on my machine, when "\\n"
is not printed, i
is 32767
;通过我机器上的
gdb
,当没有打印"\\n"
, i
是32767
; when "\\n"
is printed, i
happens to be 0
.打印
"\\n"
, i
恰好是0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.