0
#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?

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by Adak
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.