I was working on pop and push methods on the stack. Actually in this code I am creating dynamic array using pointers and malloc function. Then I was trying to add or delete elements to dynamic array with pop and push methods.But I getting the error in the question. I can't see any error in the code. Can you help me?
Here my main.c file
#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 file
#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 file
#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;
}
CodePudding user response:
After #define main
in “main_header.h”, the code int main(){
in “test_stack.c” is replaced by int (){
. This causes the syntax error that the compiler (not Xcode) reports.
Do not use main
in “main_header.h” as an indicator for whether the header file has been included already. Use some other name that you will not use for anything else, such as main_h
or main_header_h
.
(Clang is the compiler. Xcode is the overall integrated development environment that facilitates use of the compiler, organizes your projects files, opens editors, maintains your project options, and so on.)