How can I place a pre set array of a struct in a different struct?

164 Views Asked by At

I'm going through something that should be simple in C but for some reason cant seem to get it to work.

Here are the structs:

    #define MAX_BRANCH 500
    #define MAX_BANK_CLIENTS 100000
    #define MAX_CLIENTS 10000


   typedef struct Client{
        char *pName;
        char *fName;
        int id;
        int branch;
        int AccountNum;
        int credit;
        double surplus;
        double IOU;
        double savings;
    }Client;

   typedef struct Branch{
        int BrnachNum;
        char *Name;
        int Accounts;
        double sumOfAll;
        double profit;
        int ActiveLoans;
        int Opened;
        int Closed;
        Client ClientList[MAX_CLIENTS];
    }Branch;

    typedef struct Bank{
        char *Name;
        int Branches;
        int Accounts;
        int ActiveLoans;
        double sumOfAll;
        double Profit;
        Branch BranchList[MAX_BRANCH];
    }Bank;




int main()
{
   Bank Discount;
   Discount.BranchList[0].Accounts = 1;

   return 0;
}

//--------------------------------------------

this simple placement of an integer value to an integer argument shows me a stack overflow or any other accesses to the inner fields and the char pointer will be assigned by strdup(the only memory allocation i can use).

And just keep in mind that I cant use memory allocation of any kind.

Second is, some one instructed me to set a static array of the struct. Something like

static Branch BranchList[500]

but how can I do the same for each of the branches?

2

There are 2 best solutions below

3
On

The problem seems to be that you're using structs before they've been declared. You might want to define them in the reverse order.

6
On

First, change the order of the structs in order to do away with compilation errors. And then, coming to your problem of stack overflow, you are really using HUGE arrays and if you have these inside a function, then you just declare one variable of each struct you should get a stack overflow in all probability.

Converting them to static, might save you as you would be pushing them onto the data section rather than the stack. But this depends on the data section allocated to your process which in turn depends on the system ( OS ) you are running on.

And once you do,

 static Branch BranchList[500];

you are allocating space for all branches, so where is the question of each branch?

As you are ruling out malloc and if static isn't solving your problem, try increasing stack size using setrlimit