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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.