Reputation: 131
in this program, I need to store the frequency of the ascii characters i read in an array (in order to print the most frequent). the problem is that what i get from read is not ascii (most probably some kind of address) so in the buf[] array i get out of bounds. Can anybody tell help me with that?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<strings.h>
#define MODEMDEVICE "/dev/ttyAMA0"
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
int main()
{
int fd,c, res=0,i;
struct termios oldtio,newtio;
int buf[128] ;
for (i=0;i<128;i++) buf[i]=0;
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd <0) {perror(MODEMDEVICE); exit(-1); }
tcflush(fd, TCIFLUSH);
while (STOP==FALSE) { /* loop until we have a terminating condition */
int r=read(fd,&c,1);
write(1,&c,1);
if (c=='\n') {
for(i=0;i<128;i++)
if (res < buf[i] )
res = buf[i];
printf("first char %d \n", res);
}
else {
buf[c]++;
}
}
}
Upvotes: 0
Views: 132
Reputation: 2292
int c
creates a variable of probably 4 bytes. It is not initialized, thus it may contain any garbage.
Then the system call
read(fd,&c,1)
changes one of these bytes, probably the highest or lowest, while leaving the others unchanged. Now you have a combination of 3 bytes of random garbage plus the one byte fresh from fd, placed somewhere in c.
And then you try to get sense out of that combination.
Things might work much better if you define c as char
:
char c;
Upvotes: 2