Currently I have the following code below. char **arr
is initially set to NULL
. then it stores in words while reading from a file. I just randomly chose a large number like 5000
because I don't understand how to do malloc
business properly, even after looking online and trying to learn.
Also, when I try to free
char **arr
(the last section of my code), sometimes I get segmentation faults
, sometimes abort traps
, etc. If someone could show me how to do something like this properly that would be highly appreciated! Thanks!
char **arr = NULL
File *fp = fopen("file.txt", "r")
char string[3000];
char counter = 0;
//to store
while(fscanf(fp, "%s", string)!=EOF){
arr = realloc(arr, 5000); //arbitrarily used a large number like 5000
arr[counter] = malloc(5000);
strcpy(arr[counter++], string);
}
//to free
for(i=0; i<counter; i++){
free(arr[i])
}
free(arr);