How to populate Dynamic array with Strings in C -


i doing project have read in text file , extract every word 4 characters long , allocate dynamic array.my approach create int function number of 4 letter words , return number , create function grab number , create dynamic array consisting of many elements. problem approach how populate array words meet requirement.

int func1(file *pfile){      int counter = 0;     int words = 0;     char inputwords[length];     while(fscanf(pfile,"%s",inputwords) != eof){     if(strlen(inputwords)==4){           #counting 4 letter words           counter++;            }       }  }       return counter;  }     int main(){     #creating pointer textfile     file *pfile = fopen("smalldictionary.txt","r");     int line = 0;       #sending pointer function        func1(pfile);     fclose(pfile);     return 0; } 

i suggest reading lines of input fgets(), , breaking each line tokens strtok(). each token found, length can checked, , if token 4 characters long can saved array using strdup().

in code below, storage allocated pointers char store addresses of four-letter words. num_words holds number of four-letter words found, , max_words holds maximum number of words can stored. when new word needs added, num_words incremented, , if there not enough storage, more space allocated. strdup() used duplicate token, , address assigned next pointer in words.

note strdup() not in c standard library, posix. feature test macro in first line of program may needed enable function. note strdup() allocates memory duplicated string must freed caller.

#define _posix_c_source 200809l  #include <stdio.h> #include <stdlib.h> #include <string.h>  #define buf_sz     1000 #define alloc_inc  100  int main(void) {     file *fp = fopen("filename.txt", "r");     if (fp == null) {         perror("unable open file");         exit(exit_failure);     }      char buffer[buf_sz];     char **words = null;     size_t num_words = 0;     size_t max_words = 0;     char *token;     char *delims = " \t\r\n";      while (fgets(buffer, sizeof buffer, fp) != null) {         token = strtok(buffer, delims);          while (token != null) {             if (strlen(token) == 4) {                 ++num_words;                 if (num_words > max_words) {                     max_words += alloc_inc;                     char **temp = realloc(words, sizeof *temp * max_words);                     if (temp == null) {                         perror("unable allocate memory");                         exit(exit_failure);                     }                     words = temp;                 }                 words[num_words-1] = strdup(token);             }             token = strtok(null, delims);         }     }      if (fclose(fp) != 0) {         perror("unable close file");         exit(exit_failure);     }      (size_t = 0; < num_words; i++) {         puts(words[i]);     }      /* free allocated memory */     (size_t = 0; < num_words; i++) {         free(words[i]);     }     free(words);      return 0; } 

update

op has mentioned nonstandard functions not permitted in solving problem. though strdup() posix, , both common , standard in sense, not available. in such circumstances common implement strdup(), straightforward so. here above code, modified function my_strdup() used in place of strdup(). code unchanged, except feature test macro has been removed, call strdup() has been changed my_strdup(), , of course there function prototype , definition my_strdup():

#include <stdio.h> #include <stdlib.h> #include <string.h>  #define buf_sz     1000 #define alloc_inc  100  char * my_strdup(const char *);  int main(void) {     file *fp = fopen("filename.txt", "r");     if (fp == null) {         perror("unable open file");         exit(exit_failure);     }      char buffer[buf_sz];     char **words = null;     size_t num_words = 0;     size_t max_words = 0;     char *token;     char *delims = " \t\r\n";      while (fgets(buffer, sizeof buffer, fp) != null) {         token = strtok(buffer, delims);          while (token != null) {             if (strlen(token) == 4) {                 ++num_words;                 if (num_words > max_words) {                     max_words += alloc_inc;                     char **temp = realloc(words, sizeof *temp * max_words);                     if (temp == null) {                         perror("unable allocate memory");                         exit(exit_failure);                     }                     words = temp;                 }                 words[num_words-1] = my_strdup(token);             }             token = strtok(null, delims);         }     }      if (fclose(fp) != 0) {         perror("unable close file");         exit(exit_failure);     }      (size_t = 0; < num_words; i++) {         puts(words[i]);     }      /* free allocated memory */     (size_t = 0; < num_words; i++) {         free(words[i]);     }     free(words);      return 0; }  char * my_strdup(const char *str) {      size_t sz = strlen(str) + 1;     char *dup = malloc(sizeof *dup * sz);      if (dup) {         strcpy(dup, str);     }      return dup; } 

final update

op had not posted code in question when above solution written. posted code not compile is. in addition missing #includes , various syntax errors (extra braces, incorrect comment syntax) there couple of more significant issues. in func1(), length variable used uninitialized. should large enough inputwords[] can hold expected word. also, width specifiers should used %s in scanf() format strings avoid buffer overflow. and, op code should checking whether file opened successfully. finally, func1() returns value, calling function not assign value variable.

to complete task, value returned func1() should used declare 2d array store four-letter words. file can rewound, time fscanf() retrieves words in loop, if word has length 4, strcpy() used copy word array.

here modified version of op's code:

#include <stdio.h> #include <stdlib.h> #include <string.h>  #define max_word  100  int func1(file *pfile){      int counter = 0;     char inputwords[max_word];      while(fscanf(pfile,"%99s",inputwords) != eof) {         if(strlen(inputwords) == 4) {           counter++;         }     }     return counter;  }  int main(void) {     file *pfile = fopen("filename.txt","r");     if (pfile == null) {         perror("unable open file");         exit(exit_failure);     }      char inputwords[max_word];     int num_4words = func1(pfile);     char words[num_4words][max_word];     int counter = 0;      rewind(pfile);      while(fscanf(pfile,"%99s",inputwords) != eof) {         if(strlen(inputwords) == 4) {           strcpy(words[counter], inputwords);           counter++;         }     }      if (fclose(pfile) != 0) {         perror("unable close file");     }      (int = 0; < num_4words; i++) {         puts(words[i]);     }      return 0; } 

Comments