简体   繁体   中英

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();
}

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};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM