Passing data from a two-dimensional array to a structure

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

typedef struct words {
  char *mas;
}words;

int main(void) {
  FILE *fp=fopen("test.txt", "r");
  char str[100];
  char arr[100][100];
  int k=0;
  words_in->mas=malloc(sizeof(char)*sizeof(arr));
  char *istr;
  printf("\nFile text\n\n");
    for (int i = 0; i < 3; i++) { 
        istr = fgets(str, 100, fp);
        printf("%s", istr);
        for (char* istr = strtok(str, " .\t\n"); istr; istr = strtok(NULL, " .\t\n")) {
            strcpy(arr[k++], istr);
        }
    }

How do I pass all words written to the two-dimensional array to the structure?

I want my structure to have an array of char pointers, instead of just one pointer. Or a linked list of pointers. Or an array of structs.

And is it possible to somehow dynamically allocate memory for the structure and for arrays?

Upvotes: 1

Views: 70

Answers (1)

m0hithreddy
m0hithreddy

Reputation: 1829

If you want to prevent two loops and you are ready to sacrifice some memory you can follow this approach

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

typedef struct words {
  char **mas;
}words;

int main()
{
    FILE *fp=fopen("test.txt", "r");

    struct stat statbuf;
    fstat(fileno(fp), &statbuf);

    long f_size = statbuf.st_size;

    words words_in;
    words_in.mas = (char**) malloc(sizeof(char*) * f_size); // In worst case each byte is one word.

    char fbuf[f_size+1];    // In worst case all bytes form one word ;

    long word_count = 0;
    while(fscanf(fp,"%s", fbuf) == 1) {
        words_in.mas[word_count] = strdup(fbuf);
        word_count++;
    }

    for (long i = 0; i < word_count; i++) {
        printf("%s\n",words_in.mas[i]);
    }
    return 0;
}

INPUT 1

Apple
Bat
Cat

OUTPUT 1

Apple
Bat
Cat

INPUT 2

AppleBatCat

OUTPUT 2

AppleBatCat

INPUT 3

Apple Bat Cat

OUTPUT 3

Apple
Bat
Cat

Upvotes: 1

Related Questions