Reputation: 155
#include <stdio.h>
#include <ctype.h>
void readFile(FILE *file);
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces);
void printMessage(int *alpha, int *digit, int *punct, int *spaces);
int main( void ) {
FILE *file = NULL;
readFile(file);
return 0;
}
void readFile(FILE *file) {
file = fopen("/Users/AdmiralDanny/Desktop/testFile.txt", "r");
int *alpha = NULL, *digit = NULL, *punct = NULL, *space = NULL;
if (file) {
count(file, alpha, digit, punct, space);
fclose(file);
} else {
perror( "error opening the file" );
}
}
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces) {
int ch;
while ((ch = fgetc(file)) != EOF ) {
if (isalpha(ch) != 0) {
++alpha;
} else if (isdigit(ch)) {
++digit;
} else if (ispunct(ch)) {
++punct;
} else if (isspace(ch)) {
++spaces;
}
}
printMessage(alpha, digit, punct, spaces);
}
void printMessage(int *alpha, int *digit, int *punct, int *spaces) {
printf( "alphabetic characters: %d\n", alpha );
printf( "digit characters: %d\n", digit);
printf( "punctuation characters: %d\n", punct );
printf( "whitespace characters: %d\n", spaces );
}
my .txt file only has 4 spaces and 12 alphabet character, but it gives me 48 alphabetic characters and 8 white space characters? why is this happening? also, i get a warning when i tried to print out the int pointeres in printMessage method
Upvotes: 0
Views: 158
Reputation: 121961
No memory has been allocated for any of the int
s and the count()
function is just incrementing the int
pointers not an int
value:
++spaces; /* spaces is an int* so this increments the pointer. */
You could use malloc()
, but it would simpler to stack allocate and pass the addresses in.
int alpha = 0, digit = 0, punct = 0, space = 0;
count(file, &alpha, &digit, &punct, &space);
and in count()
:
(*spaces)++;
dereference the int
s for incrementing and dereference for printing:
printf( "whitespace characters: %d\n", *spaces);
As the caller of count()
does not require the updated values of the int
s, just pass by value and forget about pointers altogether (same for printMessage()
).
Upvotes: 2
Reputation: 11910
you can print address what pointer points to:
printf( "alphabetic characters: %p \n", alpha );
if you want just the value:
printf( "alphabetic characters: %d\n", *alpha );
same as *digit, *punct ....
Upvotes: 0