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

typedef struct {
int tos;
char stackarr[];
}STACK;

STACK paren;
paren.tos = -1;

void push()
{
paren.tos++;
paren.stackarr[tos] = '(';
}

This is giving me the following error:

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
paren.tos = -1;
     ^
In function ‘push’:
error: ‘tos’ undeclared (first use in this function)

I'm a beginner and have no idea why I'm getting this error. Any ideas?

anonymous2
  • 219
  • 7
  • 21
azemda
  • 79
  • 1
  • 1
  • 8

1 Answers1

3

You cannot perform an assignment outside a function; only initialization is allowed (demo):

STACK paren = {.tos = -1};

With this part out of the way, your approach is not going to work: flexible members, i.e. char stackarr[] at the end of the struct, do not work in statically allocated space; you need to use dynamic allocation with them. See this Q&A for an illustration of how to use flexible struct members.

Alternatively, you can pre-allocate the max number of elements to stackarr, i.e.

typedef struct {
    int tos;
    char stackarr[MAX_STACK];
} STACK;
STACK paren = {.tos = -1};

The obvious limitation to this approach is that the stack cannot grow past its preallocation limit.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523