#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int count; // counter to use the word's occurrence
    char word[99];
} word;
char str[99];
word myword[50];

int main() {


    FILE *myfile;

    if ((myfile = fopen("wordlist", "r")) == NULL) {
        printf("\n Error:Can't open file \n ");
        exit(0);
    }
    int position = 0;

    while (fscanf(myfile, "%s", str) != EOF) {
        printf("position[%d] word:<%s>\n", position, str); //let's see if i'm getting the words right
        strcpy(myword[position].word, str);
        position++;
        if (position == 50) {
            break;
        }
    }

    int i;
    for (i = 0; i < 50; i++) {
        printf("testing myword[%d].word: %s\n", i, myword[i].word);
    }
    return 0;
}

How can I dynamically allocate size of char word and char str?

malloc(SizeOfArray) is part of stdlib.h, and allocates memory "as is", in the amount you request

calloc() is also part of stdlib.h, and allocates memory which has been set to zero or '\0'.

Both of these return a valid pointer to the allocated memory, if the request was performed, and NULL otherwise. (always good to test the return on these two functions).

For code snippets showing it, look for dynamic arrays in the forum searcher.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.