简体   繁体   中英

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

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.

int words,lines,chara = 0;

sets chara to 0 but doesn't initialise the other variables. If you want to initialise all 3, you'd need

int words = 0, lines = 0, chara = 0;
int words,lines,chara = 0;

This line declares 3 variables but initializes only chara .

Later in the loop you begin incrementing words but it is not initialized yet. It has an undefined value.

You can correct it by doing simply :

int words = 0, lines = 0, chara = 0;

You missed initializing words variable

int words =0;

Uninitialized variable will have garbage value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM