-
loop crashes programme
hi,
i need help with the following part of a code...
#include <stdio.h>
#include <string.h>
main()
{
int ansi[255];
char path[128];
gets(path);
FILE *file = fopen(path, "r");
int i = 0;
int counter = 0;
char buffer[200];
int chars = 0;
char chr;
while(!feof(file))
{
fgets(buffer,200,file);
chars += strlen(buffer);
while(counter++ < strlen(buffer))
{
chr = buffer[counter];
ansi[chr] += 1;
}
counter = 0;
i++;
}
(...)
it compiles but then crashes after entering the filepath. works right without the second while-loop, btw. i wanna use the second loop to count how often different letters are used in a textfile. if buffer[counter] is 'a' (= 97 in ascii), for example, it shall add one to ansi['a'], the 97st element of ansi[].
have a nice day.
-
while(counter++ < strlen(buffer))
{
chr = buffer[counter];
ansi[chr] += 1;
}
note buffer[0] is never read
for
entering the loop for first time counter is 0
after this line : while(counter++ < strlen(buffer))
counter becomes 1
so ch takes the value buffer[1]
-
um, yeah. a mistake i didn't notice.. but it doesn't change anything and still crashes, heh.
thanks anyway.
-
while(counter < strlen(buffer))
{
chr = buffer[counter++];
ansi[chr] += 1;
}
-
>while(counter < strlen(buffer))
>{
>chr = buffer[counter++];
>ansi[chr] += 1;
>}
i fixed it this way, too. but like i said, that's not the problem! i really don't get, why the programme doesn't work... the char buffer[counter] is copied to chr and it really doesn't count if it's element 0 or 1, they both are ascii-characters. i suppose i should convert chr to another datatype while using it as index of ansi[] but i have tried that and it didn't help, too. no one any idea?
-
How about?
int ansi[256] = {0};
-
i've just compiled the code with gcc under OpenBSD instead of DevCpp under Windows 98 and it works perfectly so it seems to be a compilerspecific problem or something. thanks to you both who tried to help me.
bye.