C scanf 函数returns 元素太多
C scanf function returns too much elements
我有以下(代码here):
#include <stdio.h>
void print(char* m, int* a, int c){
printf("%s (%d els.)\n", m, c);
for(int i = 0; i < c; i++)
printf("%d ", a[i]);
printf("\n");
}
int main(void) {
int c = 0;
int a[50];
while(scanf("%d", &a[c++]) == 1);
print("Init array: ", a, c);
return 0;
}
然后输入 5 6 2 1 8 8 1
,我有以下输出:
Init array: (8 els.)
5 6 2 1 8 8 1 0
最后一个0
来自哪里?
&a[c++]
中的 c++
最后一次递增 c
,因此在您输入 n
个元素后,c == n + 1
。这就是为什么当您输入 7 个元素时您的代码会显示 (8 els.)
。 a[c - 1] == a[7]
恰好为零。
我有以下(代码here):
#include <stdio.h>
void print(char* m, int* a, int c){
printf("%s (%d els.)\n", m, c);
for(int i = 0; i < c; i++)
printf("%d ", a[i]);
printf("\n");
}
int main(void) {
int c = 0;
int a[50];
while(scanf("%d", &a[c++]) == 1);
print("Init array: ", a, c);
return 0;
}
然后输入 5 6 2 1 8 8 1
,我有以下输出:
Init array: (8 els.)
5 6 2 1 8 8 1 0
最后一个0
来自哪里?
&a[c++]
中的 c++
最后一次递增 c
,因此在您输入 n
个元素后,c == n + 1
。这就是为什么当您输入 7 个元素时您的代码会显示 (8 els.)
。 a[c - 1] == a[7]
恰好为零。