Bhagya Amarasinghe
Bhagya Amarasinghe

Reputation: 33

how do i declare an array in a struct

i did this code. I tried declaring the array in the struct as well. but i keep on getting an error message. Can someone help me :) Thank you. Have a nice day.

#include<stdio.h>
struct stack
{
    int arr[5];
    int top;
}st;


void push (int ele)
{
    st.arr[st.top]=ele;
    st.top++;
}
int pop()
{
    int item=st.arr[st.top];
    st.top--;
    return item;
}
void display()
{
    int i;
    for(i=4;i>=0;i--)
    {
        printf("%d\t",st.arr[i]);
    }
}
int main()
{
   st.arr[5]={3,6,8,7,5};
   display();
}

Upvotes: 0

Views: 45

Answers (1)

dbush
dbush

Reputation: 223699

This won't work:

st.arr[5]={3,6,8,7,5};

Because you can't assign directly to a whole array at once. What you can do however is initialize the struct along with the array it contains at the point it is defined:

struct stack
{
    int arr[5];
    int top;
} st = { {3,6,8,7,5}, 5};

Upvotes: 1

Related Questions