我正在研究堆疊上的 pop 和 push 方法。實際上在這段代碼中,我使用指標和 malloc 函式創建動態陣列。然后我嘗試使用 pop 和 push 方法向動態陣列添加或洗掉元素。但是我在問題中遇到了錯誤。我在代碼中看不到任何錯誤。你能幫助我嗎?
這是我的 main.c 檔案
#include <stdio.h>
#include <stdlib.h>
#include "main_header.h"
stack * init(){
stack *s = (stack *) malloc(sizeof(stack));
s->items = NULL;
s->top = 0;
s->count = 2;
return s;
}
int pop(stack *s){
if(s->items == NULL){
printf("Items is empty.\n");
return -1;
}
if(s->top<=s->count/4){
int *items2 = (int *)malloc(sizeof(int)*s->count/2);
for (int i = 0; i < (s->count/2); i ){
items2[i] = s->items[i];
}
free(s->items); // burada "dizi" ad?ndaki dizimiz dizi2 ile ayn? yeri g?sterdi?inde ?nceki 2 elemanl?k dizi lost in space olacak bunu ?nlemek i?in free(dizi) diyerek o 2 eleman? bellekten siliyoruz.
s->items = items2;
s->count /= 2;
}
return s->items[--s->top];
}
void push(int a, stack *s){
if(s->items == NULL){
s->items = (int *)malloc(sizeof(int) * 2);
}
if(s->top>=s->count){
int *items2 = (int *)malloc(sizeof(int)*s->count*2);
for (int i = 0; i < s->count; i )
items2[i] = s->items[i];
free(s->items); // burada "dizi" ad?ndaki dizimiz dizi2 ile ayn? yeri g?sterdi?inde ?nceki 2 elemanl?k dizi lost in space olacak bunu ?nlemek i?in free(dizi) diyerek o 2 eleman? bellekten siliyoruz.
s->items = items2;
s->count *= 2;
}
s->items[s->top ] = a;
}
void getItems(stack *s){
printf("count: %d\n", s->count);
for (int i = 0; i < s->top; i ) {
printf("%d\n", s->items[i]);
}
}
main_header.h 檔案
#ifndef main
#define main
struct s {
int count;
int top;
int *items;
};
typedef struct s stack;
stack * init(void);
int pop(stack *);
void getItems(stack *);
void push(int, stack *);
#endif
test_stack.c 檔案
#include <stdio.h>
#include <stdlib.h>
#include "main_header.h"
int main(){
stack *s1 = init();
stack *s2 = init();
for (int i = 0; i < 10; i ) {
push(i*10, s1);
}
getItems(s1);
for (int i = 0; i < 10; i ) {
push(pop(s1), s2);
}
return 0;
}
uj5u.com熱心網友回復:
#define main在“main_header.h”之后,“test_stack.c”中的代碼int main(){被替換為int (){. 這會導致編譯器(不是 Xcode)報告的語法錯誤。
不要main在“main_header.h”中使用作為頭檔案是否已經包含的指示符。使用一些不會用于其他任何內容的其他名稱,例如main_h或main_header_h。
(Clang 是編譯器。Xcode 是便于使用編譯器、組織專案檔案、打開編輯器、維護專案選項等的整體集成開發環境。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401142.html
