I want to fill an array from a function with the components of a file in c

Viewed 48

Hey I have the code below that I want to fill the dict array with the values of a file. Basically i get each line and then with the help of the four strtok functions I get the value that i want in and then i place that value on dictionary[i] so i can fill my array with all the string from the file but i get the following warning in compilation:

the error message:

warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
   38 |                         dictionary[i] = strtok(NULL, "\t");

the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypt.h>
void readDict(char dictionary[]);

void readDict(char dictionary[]) {
    
    int i =0;
    FILE *fp = fopen("dictionary/top250.txt" ,"r");
  if(fp == NULL) {
    printf("Error! opening file");
    exit(1);
  }
  char chunck[128];
  size_t len = sizeof(chunck);
  char *line = malloc(len);
  if(line == NULL){
      perror("Unable to allocate memory to buffer");
      exit(1);
  }
  line[0]='\0';
  while(fgets(chunck, sizeof(chunck), fp) != NULL){
      if(len - strlen(line) < sizeof(chunck)){
          len*=2;
          if((line = realloc(line, len)) == NULL){
              perror("Unable to reallocate memory to buffer.");
              free(line);
              exit(1);
            }
        }
        strcat(line, chunck);
        if(line[strlen(line)-1] == '\n'){
            
            char* one = strtok(line, "\t");
            char* two = strtok(NULL, "\t");
            char* three = strtok(NULL, "\t");
            dictionary[i] = strtok(NULL, "\t");
            i++;
            line[0]='\0';
        }
  } 
  fclose(fp);
    free(line);

}


int main(int arg_count, char *arg[]) {
    char dict[250];
    readDict(dict);
    int j=0;
    for( j=0; j<=250; j++){
        fputs(dict[j], stdout);
    }
    
    //Rest of the code
    
}
1 Answers

The C function strtok returns a char *, it's a pointer to a char. The thing here is that you send to your function readDict a char *, when you put an index to a char * its becomes a char, but you try to assign a variable of type (char) dictionary[i] to a char *.. coming from strtok return value !

dictionary[i] = strtok(NULL, "\t");                                             

If you wanna make a table try to make a char **, remember you can't say a char * is equal to an other ! You have to say for each char is equal to an other char, with a while / for loop.

It's only an advice, but try to allocate your strings, table, ... with malloc void * function, this is only to have a clean code without memory leak, and do not forget to free them with the free(void *) function.

Good luck anyway !

Related