Program pokazuje prostą implementację stosu zawierającego zmienne typu String, oraz unię (połączenie kilku typów) w C. Poszczególne funkcje dodają element do stosu, usuwają go, wypisują stos, lub usuwają wszystkie elementy stosu.

Kod działa w Linux i Windows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#define MAX_NAZWA 32
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct recsym
{
  char nazwa[MAX_NAZWA];
  int typ;

  union
  {
    long w_int;
    char w_char;
    double w_double;
  } wart;

  struct recsym *next;
};

struct recsym *global=0, *temp_typ=0;
//^globaly stos zmiennych globalnych


//usuwa caly stos:
void stos_del( struct recsym *stos )
{
  struct recsym *ptr=stos;
  while (ptr)
  {
    stos=ptr;
    ptr=ptr->next;
    free(stos);
  }
}


//wklada element na stos:
struct recsym *put( char *nazwa, int typ, struct recsym *stos )
{
  struct recsym *ptr;
  ptr = (struct recsym *) malloc( sizeof(struct recsym) );
  if (!ptr)
  {
    printf( "Blad! brak pamieci dla tablicy symboli!\n" );
    exit(1);
  }
     
  strcpy( ptr->nazwa, nazwa );
  ptr->typ = typ;
  ptr->next = stos;
  stos = ptr;
  return ptr;
}


//pobiera element z wierzchu stosu:
struct recsym *get( char *nazwa, struct recsym *stos )
{
  struct recsym *ptr;
  for (ptr = stos; ptr; ptr = ptr->next)
    if (!strcmp(ptr->nazwa,nazwa))
      return ptr;
     
  return 0;
}

//wypisuje zawartosc stosu
void stos_out( struct recsym *stos )
{
  struct recsym *ptr;
  printf( "\nStos:\n" );
        if (stos==0) {
    printf( " Stos jest pusty\n");
    return;
  }else printf( " Jest cos na stosie:\n");
  //petla wypisujaca stos:
  for (ptr = stos; ptr; ptr = ptr->next)
   printf( "%s : %i\n", ptr->nazwa, ptr->typ );  
}



int main()
{
 //do starego global czyli pustego - dorzucamy element
 global = put ( "gfhgfjgf1", 1, global );
 global = put ( "aaaaaaa", 2, global);
 stos_out(global); //wypisujemy
 return 0;
}
C