2016-04-15 250 views
-4

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

#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; 
} 
+0

[德雅vu..repeated ...](http://meta.stackoverflow.com/q/318618/2173917) –

+0

谢谢,对不起,C和C++标签 –

+0

“我有麻烦“在哪里?有错误吗?它以前如何? –

回答

1

指针在任何地方都没有分配。

你需要的东西是这样的:

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

上述分配一个指针,指针结构。指向结构本身的指针为null。

现在,不知道你想如果你想找到你的指针数组的末尾,假设,最后指针为NULL通过

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

达到什么样的,那么这是代码来做到这一点:

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

此外,代码中还有一些拼写错误。这将编译和工作。但我个人建议使用普通的指针数组(即只将数组的大小保存在另一个变量中)。

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; 
} 
+0

所以你在说什么 while(*(lista + i)!= NULL)i ++; 是指针指向内存的下n个位置,这n个位置是在内存中的其他位置,这就是为什么没有意义使用变量的大小来“跳”到下一个位置? –

+0

是的。好吧,lista指向指向指针的第一个指针。 lista + 1指向指针的第二个指针等等。 *(lista)指向第一个结构体,*(lista + 1)指向第二个结构体,依此类推。 – Jurys