Tablicowa implementacja stosu - co robię źle?

0

Witam!
Mam problem zaimplementowaniem stosu w postaci struktury. Konkretnie problemem jest funkcja umieszczająca nowy element na szczycie stosu. Kiedy badam program krok po kroku, na końcu funkcji push(S,x) trafia do tablicy imitującej mój stos, jednak kiedy funkcja się zakończy, na standardowym wyjściu dostaję jakąś randomową liczbę całkowitą.
Mój kod:

#include <stdio.h>

struct stack
{
  int A[100];
  int top;
};

void push(struct stack S, int x)
{
  S.top=S.top+1;
  if(S.top>100)
    printf("!BŁĄÐ! - PRZEPEŁNIENIE");
  else
    S.A[S.top-1]=x;
}

int main()
{
  struct stack S;
  S.top=0;

  push(S,15);
  int a=S.A[0];

  printf("%d", a);

  return 0;
} 

Pomysły? Z góry uprzedzam, że nie miałem wcześniej styczności ze strukturami. Każda pomoc mile widziana ;)

1

Wywołując funkcję push(), pracujesz na kopii obiektu S. Aby Twój program zadziałał, musisz przekazać parametr przez referencję, albo przyjmować wskaźnik w funkcji push().

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

#define DECL_STACK_OF(type) \
	struct type##_stack{ type *data; size_t max_elements, size; }; \
	struct type##_stack create_##type##_stack_of_size(size_t size); \
	void push_##type##_to_stack(struct type##_stack *stack, type val); \
	type get_##type##_from_stack_at(struct type##_stack *stack, size_t pos); 
	
#define DEF_STACK_OF(type) \
	struct type##_stack create_##type##_stack_of_size(size_t size){ \
		struct type##_stack result = { \
			malloc(sizeof(type)*size), \
			size, \
			0 \
		};\
		return result; } \
	void push_##type##_to_stack(struct type##_stack *stack, type val){ \
		if(stack->size < stack->max_elements){ \
			stack->data[stack->size++] = val; } } \
	type get_##type##_from_stack_at(struct type##_stack *stack, size_t pos){ \
		return stack->data[pos]; }

#define DECL_AND_DEF_STACK_OF(type) \
    DECL_STACK_OF(type) \
    DEF_STACK_OF (type)
	
DECL_AND_DEF_STACK_OF(int)

int main(void) {
	struct int_stack cont = create_int_stack_of_size(20);
	for(size_t i = 0; i < 10; ++i)
		push_int_to_stack(&cont, i);
		
	for(size_t i = 0; i < cont.size; ++i)
		printf("%d ", get_int_from_stack_at(&cont, i));
	return 0;
}

http://ideone.com/toIzQs

1 użytkowników online, w tym zalogowanych: 0, gości: 1