MALLOC function usage prob
How is my usage of malloc wrong??
Code:
typedef struct stack {
char data[SIZE_MAX]; // SIZE_MAX #defined as 100
int size;
} stack;
stack *s=(stack*)malloc(sizeof(stack)); //line# 11
output:
Code:
prg1.c:11: error: initializer element is not constant
Malloc should be used in global scope...!
Yes, as matp and others said malloc should not be used in global scope.
I've re-arranged your code to make it work...!
Code:
...
#define SIZE_MAX 100
typedef struct stack
{
char data[SIZE_MAX];
int size;
} stack;
stack *s;
void init_stack()
{
s->size=0;
return;
}
void push(char c)
{
if(s->size<SIZE_MAX)
{
s->data[(s->size)++]=c;
}
else
printf("\nStack Full!\n");
return;
}
char pop()
{
if(s->size==0)
{
printf("\nStack Empty!\n");
return('~');
}
else
return s->data[--(s->size)];
}
int main(void)
{
int t,i,j=0;
char expressions[100][400],ch;
s = (stack *) malloc(sizeof(stack));
printf("no. of expressions:");
scanf("%d",&t);
printf("enter the expressions");
for(i=0;i<t;i++)
{
printf("expr[%d]:",i+1);
scanf("%s",expressions[i]);
}
for(i=0;i<t;i++)
{
init_stack();
while(j<strlen(expressions[i]))
{
ch=expressions[i][j++];
if(isalpha(ch))
{
printf("%c",ch);
}
else if(ch==')')
{
ch=pop();
if(ch!='~') printf("%c",ch);
}
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^')
{
push(ch);
}
}
}
return 0;
}