[英]What is wrong with this simple code?
I know this might be a simple error however i still cant figure out the error. 我知道这可能是一个简单的错误,但是我仍然无法找出错误。 I am getting
我正进入(状态
the pointer address instead of the value when i print out an integer number. 当我打印出整数时,使用指针地址而不是值。
#include<stdio.h>
int main(){
char s1[100];
int words,lines,chara = 0;
FILE * fp;
fp = fopen("fox.txt","r");
if(fp==NULL){
printf("Can't open file");
}
else{
while (fscanf(fp,"%s",s1) != EOF){
words++;
// printf("%s",s1);
}
}
printf("There are %d of words",words);
}
fox.txt fox.txt
The quick
brown fox
jumps over
the lazy
dog
output : 输出:
There are 2665625 of words
words
isn't initialised so you start incrementing from an undefined value. words
未初始化,因此您将从未定义的值开始递增。
int words,lines,chara = 0;
sets chara
to 0 but doesn't initialise the other variables. 将
chara
设置为0,但不初始化其他变量。 If you want to initialise all 3, you'd need 如果要初始化所有3个,则需要
int words = 0, lines = 0, chara = 0;
int words,lines,chara = 0;
This line declares 3 variables but initializes only chara
. 该行声明3个变量,但仅初始化
chara
。
Later in the loop you begin incrementing words
but it is not initialized yet. 在循环的后面,您开始增加
words
但尚未初始化。 It has an undefined value. 它具有未定义的值。
You can correct it by doing simply : 您可以通过简单地执行以下操作来纠正它:
int words = 0, lines = 0, chara = 0;
You missed initializing words
variable 您错过了初始化
words
变量
int words =0;
Uninitialized variable will have garbage value. 未初始化的变量将具有垃圾值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.