使用堆栈添加2个大数字?

时间:2015-05-21 15:22:04

标签: c stack

我目前正在学习C编程语言(它也是我的第一个编程语言)。我现在正在处理使用堆栈添加2个大数字的问题。我已经写了一些代码来解决它,但我遇到了一些错误。

这是我的代码。

主程序

#include "stack.h"
#include <string.h>

int main(){
  node *top1,*top2,*top3;
  int i=0,n1,n2,flag=0,adder;
  char number1[50],number2[50];
  printf("Enter the first number: ");
  scanf(" %s",number1);
  printf("Enter the second number: ");
  scanf(" %s",number2);
  n1 = strlen(number1);
  n2 = strlen(number2);

  while (i<=n1 || i<=n2){
    push(top1,(number1[i]-'0'));
    push(top2,(number2[i]-'0'));
    i++;
  }

  while(!isEmpty(top1) || !isEmpty(top2)){
    adder = pop(top1) + pop(top2) + flag;
    if (adder >= 10) {
      push(top3,adder-10);
      flag = 1;
    } else {
      push(top3,adder);
      flag=0;
    }
  }
  printf("The result is: ");
  while (!isEmpty(top3)){
    printf("%d",pop(top3));
  }
  printf("\n");
  return 0;
}

stack.h lib

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

typedef int ElementType;
typedef struct node_t {
  ElementType data;
  struct node_t *next;
}node;

int isEmpty(node *top){
  return (top==NULL);
}

void push(node *top,ElementType value){
  node *p;
  p = (node*)malloc(sizeof(node));
  if (p==NULL) {
    printf("Allocation failed!\n");
    exit(0);
  }
  p->data = value;
  p->next=top;
  top = p;
}

ElementType pop(node *top){
  if (isEmpty(top)){
    printf("The stack is empty!\n");
    return 0;
  } else {
  node *p;
  ElementType value;
  value = top->data;
  p = top;
  top = top->next;
  free(p);
  return value;
  }
}

它完成了编译但是当我输入2个数字时,会出现Core Dump错误。我试图用gdb来查找结果。

#0  0x00007ffff7a44267 in __GI_raise (sig=sig@entry=6)
    at ../sysdeps/unix/sysv/linux/raise.c:55
#1  0x00007ffff7a45eca in __GI_abort () at abort.c:89
#2  0x00007ffff7a87c53 in __libc_message (do_abort=do_abort@entry=1, 
    fmt=fmt@entry=0x7ffff7ba01a8 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff7a939f8 in malloc_printerr (ptr=<optimized out>, 
    str=0x7ffff7ba01d0 "munmap_chunk(): invalid pointer", 
    action=<optimized out>) at malloc.c:4965
#4  munmap_chunk (p=<optimized out>) at malloc.c:2820
#5  __GI___libc_free (mem=<optimized out>) at malloc.c:2945
#6  0x000000000040083c in push (top=0x7fffffffe201, value=1) at stack.h:24
#7  0x0000000000400955 in main () at teststack1.c:16
(gdb) 

1 个答案:

答案 0 :(得分:1)

分段错误可能是因为您正在释放top函数中的push。你真的不想这样做,因为调用代码正在使用它。但该计划还存在其他一些缺陷。例如:
代码中的逻辑是错误的:

while(!isEmpty(top1) || !isEmpty(top2)){
    adder = pop(top1) + pop(top2) + flag;
.....

<{strong> top1top2非空时,条件为真。这意味着其中一个可以为空。但后来你试图从他们两个人pop,甚至是空洞的人。