Sheesh, are CT and grumpy jacking you around?
Originally Posted by
mdarda
I thought that with the for statement i can alloc space for argc-2 pointers (words pointers) thats why i'm incementing word++ that i could use them as a static array with [i] index, am I wrong?
You do allocate the space, and that would be okay except:
1) words itself is supposed to be an array of pointers, but you never initialize it as such. Not only does every pointer in the array need to be allocated dynamically, but so does the array itself (see below).
2) You increment words in the initial for loop, so at the end, words does not point to the same place anymore. You would then need to rewind it:
Code:
words -= i; // pointer arithmetic uses unit size of type
However, that is sort of an unorthodox method. Your original for(i) loop in post #1 was correct, just you did not allocate for the array before you allocated its members.
Here's an example of part of what you are trying to do. It reads a list of words from standard input into an array of structs, dynamically allocated. You must specify how many words via a command line parameter, eg:
echo "one two three four five" | ./a.out 5
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char *word;
int count;
} storage;
storage *addWord (char *input) {
// allocate, initialize, and return a new struct
storage *rv = malloc(sizeof(storage));
rv->word = malloc(strlen(input));
strcpy(rv->word, input);
rv->count = 1;
return rv;
}
void freeStorage (storage **p) {
// deallocate struct
free((*p)->word);
free(*p);
}
int main(int argc, char *argv[]) {
int i, total = strtol(argv[1], NULL, 0);
// declare AND INITIALIZE words properly
storage **words = malloc(total * sizeof(storage*));
char data[1024];
// simultate file input
for (i = 0; i < total; i++) {
// check for error when reading
if (fscanf(stdin, "%s", data) != 1) break;
words[i] = addWord(data);
}
// check
for (i = 0; i < total; i++)
printf("%s (%d)\n", words[i]->word, words[i]->count);
// cleanup
for (i = 0; i < total; i++) freeStorage(&words[i]);
free(words);
return 0;
}
So there is your **pointer array, and a function which returns a *pointer designed for it. Notice the malloc() on words is for sizeof(storage*) not sizeof(storage) -- the second one is used to allocate structs in the for loop, but the first one is for the pointers to the structs. Make sense?
Output:
one (1)
two (1)
three (1)
four (1)
five (1)