【问题标题】:Pointer to pointer to Struct [closed]指向指向结构的指针的指针[关闭]
【发布时间】:2016-04-15 14:15:39
【问题描述】:

我正在尝试做一个接收字符串并将它们动态存储到结构中的 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;
}

【问题讨论】:

  • 谢谢,对于 C 和 C++ 标记感到抱歉
  • “我遇到了麻烦” 在哪里?有错误吗?那是什么?
  • 问题不在代码上,问题是我没有成功构建这个系统。
  • SO 的存在是为了帮助解决特定问题,而不是为您实施它们。你在什么方面没有成功?这个程序在编译时做了什么?你想让它做什么呢?

标签: c string pointers struct


【解决方案1】:

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

你需要这样的东西:

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

上面分配了一个指向结构体的指针。指向结构本身的指针为空。

现在,不知道你想达到什么目的

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

如果你想找到指针数组的末尾,假设最后一个指针为 NULL,那么这就是执行此操作的代码:

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

【讨论】:

  • 所以你在说什么 while (*(lista + i) != NULL) i++;是不是指针没有指向内存的下 n 个位置,这 n 个位置在内存中的其他位置,这就是为什么使用变量的大小“跳转”到下一个位置是没有意义的?
  • 是的。好吧,lista 指向第一个指向指针的指针。 lista + 1 指向第二个指针,以此类推。 *(lista) 指向第一个结构,*(lista+1) 指向第二个,依此类推。
猜你喜欢
  • 2017-09-01
  • 1970-01-01
  • 2018-05-16
  • 2016-03-21
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
相关资源
最近更新 更多