c - Why is my code outputting random numbers even though they are just counts? -


i starting learn c. trying make code count amount of a's , a's in sentence code gives me random numbers every time executed if same sentence.

#include <stdio.h> #include <string.h>  int main() {     char words[10000000000];     int i;     int acount = 0;     int acount = 0;     char a[0]="a";     char a[0]="a";     printf("input sentence counted.");     scanf("%s",words);     printf("%s",words);     (i=0;i<=sizeof(words);i++)     {         if (words[i]==a[0]){             acount++;         }else if (words[i]==a[0]){             acount++;         }     }     printf ("\nthe number of a's %i. number of a's %i.",acount,acount);     return 0;  } 

why code outputting random numbers though counts?

because you're counting uninitialized memory, given code posted.

this uninitialized:

char words[10000000000]; 

(if 10 gb fits....)

this sets memory in words string that's read, plus terminating '\0' character:

scanf("%s",words); 

assuming works, anyway. don't check return value, maybe didn't work...

now loop do? (ignoring fact int isn't big enough index 10gb array...)

for (i=0;i<=sizeof(words);i++) {     if (words[i]==a[0]){         acount++;     }else if (words[i]==a[0]){         acount++;     } } 

that loop check every char in array word , compare either 'a' or 'a'. every last 10 billion or of them, many if not of them containing unknown values.

it check 1 char past end of word. that's not good. not check past end of word:

size_t i;  ... (i=0;i<sizeof(words);i++) {     if (words[i]==a[0]){         acount++;     }else if (words[i]==a[0]){         acount++;     } } 

note change < instead of <=, , use of size_t i instead of int.

even better, don't try counting random data:

size_t i;  ... (i = 0; words[i]; i++) {     if (words[i] == a[0]) {         acount++;     } else if (words[i] == a[0]) {         acount++;     } } 

since string ends in '\0' char value, loop end when words[i] has 0 value.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -