Using C Pointer Pointer

Asked

Viewed 125 times

1

hello

I’m doing a work of algorithms in C and stopped at one part. The program has to read from an input file and insert into an n-ary Trie tree.

The code that reads from the file is this:

int abre_arquivo(TRIE_N ** root) {

  FILE* arquivo;

  char* word;

  arquivo = fopen("dicionario.txt", "r");

  if (arquivo == NULL)

    printf("Arquivo não pode ser aberto.\n");

  else {

    while ((fscanf(arquivo, "%s\n", word)) != EOF) {

      insertTrie(&(*root), word);

    }

  }

  fclose(arquivo);

  return 0;

}

the header of the insertTrie function is:

int insertTrie(TRIE_N ** root, char * word) 

I wanted to know how to call the job insertTrie within the file correctly. I used gdb and is giving segmentation failure in line

current = &(*root)->children[word[0]-97];

of insertTrie. If there is any other error in the function would like to know too.

Thank you

  • root has not changed in abre_arquivo, simply passed to insertTrie. (But why write &(*root) in abre_arquivo when you can write root?) It seems to me that it would be more important to demonstrate what value has passed to abre_arquivo, and the content of insertTrie.

  • 2

    You’re not allocating your pointer word, when you try to enter value or write what you have inside, you find nothing and the memory error.

1 answer

1

Try to do

char word[50];

and in the function call

insertTrie(root, word);

I think that solves your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.