V
Vlad Dogaru
Hello,
I am trying to learn C, especially pointers. The following code
attempts to count the appearences of each word in a text file, but
fails invariably with Segmentation Fault. Please help me out, I've
already tried all my ideas. Also, please do comment on my coding style
or other aspects. Thank you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INITLEN 5
#define DELTA 5
int main(int argc, char **argv)
{
char **words, *word, *string;
int *apps, max, found, i, n;
FILE *input;
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 0;
}
max = INITLEN;
n = 0;
words = (char **) calloc(max, sizeof (char *));
apps = (int *) calloc(max, sizeof (int));
input = fopen(argv[1], "r");
while (fgets(string, 1000, input)) {
word = strtok(string, " ");
while (word) {
found = 0;
for (i=0; i<n; i++)
if (!strcmp(words, word)) {
found = 1;
apps++;
break;
}
if (!found) {
words[n] = strdup(word);
apps[n] = (int) malloc(sizeof(int));
apps[n] = 1;
n++;
if (n == max) {
max += DELTA;
words = (char **) realloc(words, max);
apps = (int *) realloc(apps, max);
}
}
word = strtok(NULL, " ");
}
}
for (i=0; i<n; i++)
printf("Word '%s' appears %d time(s).\n", words, apps);
return 0;
}
I am trying to learn C, especially pointers. The following code
attempts to count the appearences of each word in a text file, but
fails invariably with Segmentation Fault. Please help me out, I've
already tried all my ideas. Also, please do comment on my coding style
or other aspects. Thank you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INITLEN 5
#define DELTA 5
int main(int argc, char **argv)
{
char **words, *word, *string;
int *apps, max, found, i, n;
FILE *input;
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 0;
}
max = INITLEN;
n = 0;
words = (char **) calloc(max, sizeof (char *));
apps = (int *) calloc(max, sizeof (int));
input = fopen(argv[1], "r");
while (fgets(string, 1000, input)) {
word = strtok(string, " ");
while (word) {
found = 0;
for (i=0; i<n; i++)
if (!strcmp(words, word)) {
found = 1;
apps++;
break;
}
if (!found) {
words[n] = strdup(word);
apps[n] = (int) malloc(sizeof(int));
apps[n] = 1;
n++;
if (n == max) {
max += DELTA;
words = (char **) realloc(words, max);
apps = (int *) realloc(apps, max);
}
}
word = strtok(NULL, " ");
}
}
for (i=0; i<n; i++)
printf("Word '%s' appears %d time(s).\n", words, apps);
return 0;
}