指向Struct的指针

时间:2016-04-15 14:15:39

标签: c string pointers struct

我正在尝试做一个接收字符串并将它们动态存储到结构中的C程序,并且在传递字符串之后,我会显示它们的女巫最多。但是我在编写指向结构指针的指针时遇到了麻烦。我正在尝试做一些像我绘制的图像here

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

struct Word{
   char* palavra;
   int aparicoes;
} ;

struct word createWord(char* str){
   struct Word *newWord = malloc(sizeof(struct Word));
   assert(newWord != NULL);

   newWord->palavra = strdup(str);
   newWord->aparicoes = 1;

   return newWord;
}

int main (){
  char* tempString;
  struct Word** lista;
  int triggrer = 1;
  int i = 0;

  while (triggrer == 1)
  {
    scanf("%s", tempString);

    if (strcmp(tempString , "fui") == 0) 
      triggrer = 0;
    else 
    {

        while(*(&lista+i*sizeof(lista)) != NULL){
            i++;
        }

        if(i == 0){
            lista = malloc(sizeof(struct Word));

        }
        else{
            lista = (struct Word*) realloc(lista, sizeof(struct Word) + i*sizeof(struct Word));
        }

    }
  }

  return 0;
}

1 个答案:

答案 0 :(得分:1)

There is no allocation of the pointers anywhere.

You need something like this:

lista = (struct Word**) malloc(sizeof(struct Word*));
*lista = NULL;

the above allocate one pointer to pointer to struct. the pointer to struct itself is null.

Now, not sure what you want to achieve by

while(*(&lista+i*sizeof(lista)) != NULL){
        i++;
    }

If you want to find the end of you array of pointers, presuming that the last pointer is NULL, then this is the code to do it:

while (*(lista + i) != NULL) i++;

Also, there are some typos in the code. This would compile and work. But I personally, recommend to use normal array of pointers (i.e. just keep the size of the array in another variable).

struct Word{
   char* palavra;
   int aparicoes;
} ;
struct Word * createWord(char* str){
   struct Word *newWord = (struct Word *)malloc(sizeof(struct Word));
   newWord->palavra = strdup(str);
   newWord->aparicoes = 1;
   return newWord;
}
int main()
{
  char tempString[1024];
  struct Word** lista;
  int triggrer = 1;
  int i = 0;
  lista = (struct Word**)malloc(sizeof(struct Word*));
  *lista = NULL;
  while (triggrer == 1)
  {
scanf("%s", tempString);

if (strcmp(tempString , "fui") == 0) 
  triggrer = 0;
else 
{

    while(*(lista+i) != NULL){
        i++;
    }

    lista = (struct Word**)realloc(lista, (i+1) * sizeof(struct Word*));
    *(lista+i) = createWord(tempString);
    *(lista+i+1) = NULL;
}
  }
  return 0;
}