Declaring size of stack from input file

This is a discussion on Declaring size of stack from input file within the C Programming forums, part of the General Programming Boards category; I need to create a stack, but the size of the stack needs to be scanned in from an input ...

  1. #1
    Registered User alpine's Avatar
    Join Date
    Oct 2010
    Posts
    6

    Declaring size of stack from input file

    I need to create a stack, but the size of the stack needs to be scanned in from an input file. How do I go about declaring the structure for the stack?

    Code:
    struct stack {
    	
    	int items[SIZE];
    	int top;
    };
    where SIZE is the number that's read in from the input file in main

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Dynamically allocate it.
    Code:
    struct stack
    {
        int *items;
        size_t maxitems;
        int top;
    };
    ...
    foo.maxitems = something i read from a file
    foo.items = malloc( maxitems * sizeof *foo.items );
    ...
    free( foo.items );
    There's a tutorial on it in the FAQ.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User alpine's Avatar
    Join Date
    Oct 2010
    Posts
    6
    So could I malloc the space from within my stack initialization function? Would that be the best route, or should I allocate the space before the stack gets initialized?
    Here's the function:

    Code:
    void initialize(struct stack* stackPtr) {
    	stackPtr->top = -1;
    }

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You could make your initialize function do it for you. It depends on what you use that function for, but since it's called 'initialize', it might not be a bad spot for it, provided you add an argument for the size you want it initialized as.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. IDE for C embedded advanced editing
    By Undici77 in forum Tech Board
    Replies: 32
    Last Post: 01-16-2010, 04:17 PM
  2. Adventures in labyrinth generation.
    By guesst in forum Game Programming
    Replies: 8
    Last Post: 10-12-2008, 01:30 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21