2016-09-05 91 views
1

我試圖通過將其所有函數寫入單獨的源文件中來實現堆棧。但是,我收到了很多錯誤,指出不兼容的指針類型。當我包含這些錯誤時不顯示主C文件中的函數。這些是我的文件。我對這個是新的。幫助我糾正它們。 謝謝。 我的主要代碼將代碼放置在多個文件中的堆棧實現

#include "myfunctions.h" 
int main() 
{ 
    int operation,data; 
    struct stack *One = (struct stack *)malloc(sizeof(struct stack)); 
    One->top = -1; 
    printf("stack functionality \n"); 
    while(1) 
    { 
     if (isEmpty(One)) 
     { 
      printf("enter 1 to push \n"); 
      scanf("%d",&operation); 
     } 
     else if (isFull(One)) 
     { 
      printf("stack is full.enter 2 to pop or 3 to diplay \n"); 
      scanf("%d",&operation); 
     } 
     else 
     { 
      printf("enter 1 to push,2 to pop,3 to display 4 to exit \n"); 
      scanf("%d",&operation); 
     } 
     switch (operation) 
     { 
      case 1: printf("enter data to be pushed \n"); 
       scanf("%d",&data); 
       push(One,data); 
       break; 
      case 2: printf("%d \n",pop(One)); 
       break; 
      case 3: display(One); 
       break; 
      case 4:exit(0); 
     } 
    } 
} 

stackfns代碼

#include <myfunctions.h> 
bool isEmpty(struct stack *b) 
{ 
    if(b->top == -1) return true; 
    else return false; 
} 
bool isFull(struct stack *b) 
{ 
    if(b->top == 9) return true; 
    else return false; 
} 
void push(struct stack *b,int data) 
{ 
    b->a[++(b->top)] = data; 
} 
int pop(struct stack *b) 
{ 
    return (b->a[(b->top)--]); 
} 
void display(struct stack *b) 
{ 
    int i; 
    for (i=0;i<10;i++) 
     printf("%d ",b->a[i]); 
    printf("\n"); 
} 

頭文件

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 
extern bool isEmpty(struct stack *b); 
extern bool isFull(struct stack *b); 
extern void push(struct stack *b,int data); 
extern int pop(struct stack *b); 
extern void display(struct stack *b); 
#define max_size 10 
struct stack 
{ 
    int a[max_size]; 
    int top; 
}; 
+0

您是如何編制的? – ilent2

+0

Gcc file1.c stackfns.c – th3465

+0

函數名通過原型語句總是可見的,所以不需要'extern'修飾符。注意:另一個文件中的數據是否需要'extern'修飾符 – user3629249

回答

1

在頭文件,你需要先decalre的結構:

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

#define max_size 10 
struct stack 
{ 
    int a[max_size]; 
    int top; 
}; 

extern bool isEmpty(struct stack *b); 
extern bool isFull(struct stack *b); 
extern void push(struct stack *b,int data); 
extern int pop(struct stack *b); 
extern void display(struct stack *b); 

在另外,不需要公開數據結構的內部實現。你可以這樣做:

.h文件中:

typedef struct xx_t xx_t; 

.c文件:

struct xx_t { 
    ... 
}; 
+0

在C中,我不認爲你需要*在函數聲明之前聲明結構,但它絕對是一個好主意。 「C語言的老版本沒有原型,函數聲明只指定了返回類型,沒有列出參數類型。」 – ilent2

+0

它的工作,感謝。 – th3465

+0

我不明白你的答案的內部實現隱藏部分。實際上,你可以解釋 – th3465