Thread: How to initalize a basic Stack of ints

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    2

    How to initalize a basic Stack of ints

    Hey people! I've been a frequent reader of these board, one of the best when it comes to C programming. I'm a newbie and hopefully someday I'll become as good as some of you.

    I have to write a code using stacks and arrays to add very big numbers. I already developed the algorithm for the whole program but the stack commands dont seem to work. (Stack new concept)

    Our teacher explained the theory behind it very well, but gave us no code whatsoever.


    How can I initialize a simple Stack of Integers, just for pop and push commands?
    I thought of this but won't compile either
    Code:
    Stack stack1, stack2;
    //to push: stack1.push(n);
    //to pop: stack1.pop();
    Thanks a lot for your time!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There aren't objects in C like there are in C++ where you can have functions called from members of the structure. Use your search engine of choice or the forum search to search for stacks. I'm sure you'll find plenty of working (and not working) examples.

    I suspect the reason you weren't given any code is so you'd write your own.


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

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Well, for starters, that looks an awful lot like C++ code, not C.

    To implement a stack you can use a simple array. You'll want a variable that keeps track of the top of the stack. Say you want your stack to be able to hold up to 10 values:
    Code:
    int stack[10];
    int stack_top = 0;
    You're push function would simply store the desired value at the top of the stack and increment the stack_top variable:
    Code:
    stack[stack_top++] = value;
    Of couse you'll want to check to make sure stack_top isn't greater than 10 or whatever size your stack is to avoid an overflow. You can get around the limitation of a set stack size by using dynamic memory allocation.

    Your pop() function would simply return the top value in the stack and decrement the stack_top variable:
    Code:
    return stack[--stack_top];
    Again, you'll have to do some bounds checking. If stack_top is 0 when pop() is called then the stack is empty and there's no value it can return.
    If you understand what you're doing, you're not learning anything.

  4. #4
    Registered User
    Join Date
    Oct 2005
    Posts
    2
    This is my first C class ever, and I did search the forum, but none of the matches found were basic enough to get me started.

    I got totally confused because they could be initialized like

    Stack stackOne[100];

    and that pop() and push() were already functions defined in C.

    Anyway, thanks a lot itsme86 for your positive reply.

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    pop() and push() were already functions defined in C.
    Huh? pop() and push() are not standard C functions...
    If you understand what you're doing, you're not learning anything.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    That doesn't initialize a stack. It simply creates an array of whatever type Stack is. See, there is no "one right way" to create a stack. A stack is a concept. How you implement it is up to you. It's like piling paper up on your desk one piece at a time. That's a stack. You take the last (top) one off first, and work your way down to the first one you placed (bottom).

    You could use an array to represent this. You could use a linked list. You could use a number of things. It's the concept you need to research. Once you have that done, it's up to you to decide how you want to implement it.


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

  7. #7
    Registered User
    Join Date
    Apr 2005
    Posts
    67
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #define STACK_SIZ 10
    long int stack[STACK_SIZ];
    int top=0;
    
    void push(long int n);
    void pop(long int n);
    
    void print_stack(void);
    
    int main(int argc,char **argv){
         long int number;
         int choice;
    start:
             printf("Insert the number you want to add(long int):\n");
             scanf("%ld",&number);
             push(number);
             printf("Wanna add another?(1-yes/0-no)\n");
             scanf("%d",&choice);
    
            if(choice==1)
                    goto start;
            else
                    print_stack();
    
            return 0;
    }
    
    void push(long int n){
            if(top>STACK_SIZ)
                    printf("Stack is full!\n");
            else
            stack[top++]=n;
      }
    I leave you to write the pop() function. Remember pop return's the number at stack[top-1]. And rearrange the code a bit. And add a check if the stack is empty. Also try to make a variable current_stack size so you only print out the numbers that are on the stack and not the rest of the empty stack like in my code. Like quazah said, there are many ways to do stack concept, but I think using array is the simplest and probabbly less powerfull. When you master arrays , pointers and structs look for linked lists.
    Last edited by blackswan; 10-07-2005 at 01:26 PM.

  8. #8
    ---
    Join Date
    May 2004
    Posts
    1,379
    Are the gotos really nessessary? That's just lazy IMO.

  9. #9
    Registered User
    Join Date
    Nov 2003
    Posts
    4

    Same Class, Diff Problem

    Here's part of my code.
    It's the file I/O that I can't seem to master.
    I added all those print statements under openFile so I could see that it was working.

    Once I read from the file how do I load the stacks I'm using?
    Shouldn't what I wrote work?
    It compiles, but I get an error saying lhs->nums not defined.

    I have all my other functions witten. What am I doing wrong?


    Code:
    typedef struct{
    	int *nums;
    	int top;
    	int max;
        }stack;
    typedef enum{TRUE, FALSE}Bool;
    int push(stack *final, int num);
    int pop(stack *final);
    /*function to add stacks*/
    void add(stack *fst, stack *snd, stack *ans);
    /*function to multiply stacks, includes negative numbers*/
    void multiply(stack *fst, stack *snd, stack *ans);
    /*Prompt user for the file name, 
    it is guaranteed they will select the correct one*/	
    void GetFile(char *fileName);
    /*Open and read the file requested*/
    void openFile(char *fileName, int *numSets);
    int main(void)
    {
    	char fileName[100];
    	int final[100], stack1[100], stack2[100], numSets;
    	stack rhs, lhs, ans;
    	rhs.max = lhs.max = ans.max = 100;
    	rhs.top = lhs.top = ans.top = -1;
    	rhs.nums = stack1;
    	lhs.nums = stack2;
    	ans.nums = final;
    	GetFile(fileName);
    	openFile(fileName,&numSets);
    	}//end main
    void GetFile(char *fileName)
    {
    	printf("Please enter the file name!\n");
    	printf("Choices are: data.txt or bonus.txt\n");
    	scanf("%s", fileName);
    }
    
    void openFile(char *fileName, int *numSets)
    {
    	int i, ch, k=0, j=0, digit=0, test=0;
    	stack *rhs, *lhs, *ans;
    	char Temp[100];
    	FILE *fp =  fopen( fileName,   "r");
    
    	  //error check
    	  if(fp == NULL)
    	  {
    		  fprintf(stderr, "Not quite what we expected!!\nHave a Nice Day!\n", fileName);
    		  exit(-1);
    	  }
    	  //Count number of sets 
    	  fscanf( fp, "%d\n" , numSets);
    	  *numSets = *numSets * 2;
    	  		
    	  for(i=0; i< *numSets; i++)
    	  {
    			j = i;
    			fscanf(fp, "%s", &Temp[i]);
    			while(Temp[j] != '\0')
    			{
                  printf("\nthis character is ' %c ' ",Temp[j]);
                  ch = Temp[j];
    			  digit = ch - '0';
                  printf("\ndigit = %d", digit);
    			  if(test==0)
                      push(rhs->nums, digit);
    			  else
    				  push(lhs->nums, digit);
    			  j++;
    			}
    			test +=1;
    			printf("\n\n");
    			if(test == 1)
    			{
    				test = 0;
    				add(rhs->nums, lhs->nums, ans);
    			}
    	  }
    	  fclose(fp);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and pointer problem
    By ramaadhitia in forum C Programming
    Replies: 2
    Last Post: 09-11-2006, 11:41 PM
  2. Confused about Memory
    By gL_nEwB in forum C++ Programming
    Replies: 22
    Last Post: 06-20-2006, 07:32 PM
  3. confused about system stack
    By George2 in forum C Programming
    Replies: 4
    Last Post: 06-05-2006, 08:14 AM
  4. Linked list Stack question
    By lyrick in forum C++ Programming
    Replies: 4
    Last Post: 09-23-2005, 06:23 AM
  5. Stack problem
    By silicon in forum C++ Programming
    Replies: 3
    Last Post: 11-11-2003, 04:30 PM