【问题标题】:Creating stack in c for structs在 c 中为结构创建堆栈
【发布时间】:2015-04-11 07:14:31
【问题描述】:

我在为某个结构实现堆栈时遇到了很多问题。我已经做了这个堆栈...

struct com_stack
{
  unsigned el_num;
  command_t *stk;
  unsigned top;
};
typedef struct com_stack *com_stack_t;

我还创建了几个函数来利用堆栈。

com_stack_t build_com_stack(unsigned num)
{
  com_stack_t s;
  s=malloc(sizeof(*s));
  s->el_num=num;
  s->stk=(command_t*)malloc((sizeof(command_t))*num);
  s->top=0;
  return s;
}

void com_push (com_stack_t s, command_t input)
{
  if(s->top == (s->el_num - 1))
  {
    s->el_num+=64;
    s->stk=(command_t)realloc(s->stk, sizeof(struct command) * s->el_num);
  }
  s->stk[s->top]=input;
  s->top++;
}

command_t com_pop (command_t)
{
  if(s->top==0)
    error(1,0, "nothing to pop");
  s->top--;
  return s->stk[s->top];
}

当推送然后弹出结构指针时遇到问题。所以 command_t 是一个结构的指针,该结构在联合中具有一个 char** 的成员。在运行以下测试时,它本身可以正常工作,但是当我使用堆栈时遇到分段错误。

...
command_t com;
com=(command_t)malloc(sizeof(struct command));
com=build_scom_command(buffer, b_start, b_end);
com_stack_t cm_st;
//cm_st=(com_stack_t)malloc(sizeof(struct com_stack));
cm_st=build_com_stack(50);
com_push(cm_st,com);
command_t com_two;
com_two=com_pop(cm_st);
char* temp;
temp=(char*)malloc(1000);
temp=com_two->u.word;
unsigned i=0;
while(temp[i]!=NULL)
  printf("%c",temp[i++]);
...

char** 的第一个元素(com_two->u.word,其中 word 是 char** 的名称)是我要测试的字符串,但在 while 循环中我遇到了分段错误。任何有关如何处理堆栈的建议或帮助将不胜感激。

edit 在所有有用的输入之后,我仍然有段错误。如果这里一切正常,那么我可能应该检查我的原始代码(此时一团糟)。任何其他输入将不胜感激,如果我确实解决了这个问题,我将发布我所做的并归因于信用。谢谢

edit 2 在返回之前必须将 pop 函数更改为递减。修复了代码,所以上面现在可以正常工作了。

【问题讨论】:

  • 您的结构声明中缺少分号。
  • 哎呀,这里有错字,但它在我的原始文件中。所以这不是问题的原因。不过感谢您的回复。
  • 出于某种原因,我认为您必须施放它,您能详细说明为什么它有害吗?
  • @Jack,因为它是多余的,降低了可读性,并且可以隐藏错误(但这不是巧合,我发布了 链接。打开并阅读。)

标签: c


【解决方案1】:

您需要为s预留空间

com_stack_t build_com_stack(unsigned num)
{
  com_stack_t s;
  s->el_num=num;
  ...
  return s;
}

cm_st=(com_stack_t)malloc(sizeof(struct com_stack));
cm_st=build_com_stack(50);

应该是

com_stack_t build_com_stack(unsigned num)
{
  com_stack_t s;
  s = malloc(sizeof(*s));
  s->el_num=num;
  ...
  return s;
}

com_stack_t cm_st = build_com_stack(50);

如果你想使用(传递)在构建函数之外分配的指针:

void build_com_stack(com_stack_t s, unsigned num)
{
  s->el_num=num;
  ...
  /* return s; There is no need to return */
}

cm_st = malloc(sizeof(struct com_stack)); /* Don't cast malloc */
build_com_stack(cm_st, 50);

正如@Qix 指出的那样

struct com_stack
{
  unsigned el_num;
  command_t *stk;
  unsigned top;
} <-- You are missing a semicolon

【讨论】:

  • 您好,感谢您的及时回复。我刚试过,还是不行。另外,我不是通过发出 cm_st=(com_stack_t)malloc(sizeof(struct com_stack)); 来分配内存吗?在构建函数之外?
  • 那么,构建函数应该如何知道另一个函数中的局部变量,如果你不传递它呢?即便如此,逻辑也会很尴尬:如果构建函数既分配又初始化,你有一个很好的类似构造函数的行为,并且保证客户端代码得到一个有效的对象。
  • 我明白你的意思,我已经从其他函数中删除了 malloc。最初,我尝试在构建中分配内存,但遇到了问题(不知道正确的语法)。但是,我仍然在 while 循环周围遇到分段错误。不过谢谢。
  • 感谢@AlterMann 的提醒,我继续使用提供的建议更改了内容。
猜你喜欢
  • 2013-05-03
  • 2020-10-11
  • 2012-06-10
  • 2017-04-18
  • 2011-01-03
  • 2011-12-28
  • 2017-03-27
  • 2011-04-20
  • 2012-11-23
相关资源
最近更新 更多