-2

I want to create an array with malloc and then assign the fields of the array an output of fgets.

char *words;
words = (char *)malloc(lines*sizeof(char));
int k = 0;
words[k] = (char *)malloc(mysize*sizeof(char));

This won't work because of the missing pointer I guess. What can I do?

WedaPashi
  • 3,561
  • 26
  • 42
waayne
  • 49
  • 6

1 Answers1

2

I want to create an array with malloc and then assign the fields of the array an output of fgets. ? Then hopefully you should declare words as double pointer or array of char pointer.

One way is, by using array of char pointer like below.

char *words[lines]; /* array of pointer, lines is nothing but number of line in file */
for(int row = 0;row < lines; row++) {
    /* allocate memory for each line */
    words[row] = malloc(mysize);/* mysize is nothing but lines has max no of char i.e max no of char */
    /* now read from file */
    fgets(word[row],mysize,fp);/* reading from file(fp) & store into word[0],word[1] etc */
}

Or you can use double pointer like char **words; also.

And once job is done, at last don't forget to free the dynamically allocated memory.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • And type casting the result of `malloc()` is not required as you did like `words = (char *)malloc(lines*sizeof(char));`. Read this https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Achal May 11 '18 at 11:23
  • Because it is already a char pointer, right? Just coded it in the form we've learned in our lecture. – waayne May 11 '18 at 11:28
  • Read the link i added. Its very useful. – Achal May 11 '18 at 11:29