Results 1 to 2 of 2

Thread: Simple word Stack in C

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    183
    Any idea why this simple word stack doesn't work?

    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>

    typedef enum {FALSE, TRUE} BOOL;

    BOOL push (char d []);
    BOOL pop (char *d []);

    typedef struct _STACK {
    char data [10];
    struct _STACK *next;
    } STACK;

    STACK *sp = NULL;

    int main (void)
    {
    char x [10];
    char y [10];

    push ("hi");
    push ("hiback");
    pop(&x);
    pop(&y);

    printf("Words in stack are %s and %s", x, y);
    }

    BOOL push (char d []){

    STACK *new;

    new = (STACK *) malloc (sizeof(STACK));
    if(new == NULL)
    return FALSE;

    strcpy(new->data, d);
    new->next = sp;
    sp = new;
    //printf("%s\n", d);
    return TRUE;
    }

    BOOL pop(char *d []){
    STACK *old;

    if(sp ==NULL)
    return FALSE;

    old =sp;
    *d = old->data;
    sp = old->next;
    free(old);
    return TRUE;
    }

  2. #2
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    When you pass an array as a parameter, you are passing the address of the first element of the array. All arrays are passed by reference, not by value. It would be far too inefficient to pass arrays by value.

    This is your prototype for pop() :

    Code:
    BOOL pop (char *d []);
    You don't need to say you're passing this as a pointer, as you are already passing a pointer because it's an array. What this prototype is actually saying to the compiler is that you are passing an array of pointers, which isn't the case.

    Just change this to:

    Code:
    BOOL pop (char d []);
    and change your function to:

    Code:
    BOOL pop(char *d []){ 
         STACK *old; 
    
         if(sp ==NULL) 
              return FALSE; 
    
         old =sp; 
         strcpy(d, old->data);  // note this is changed to 'strcpy()' not '='
         sp = old->next; 
         free(old); 
         return TRUE; 
    }
    You then just pass in the array to the function. When you write the name of an array on its own with no subscript, the compiler sees that as a pointer to the array, so don't worry about passing the address of the array.
    Harry.

    "From one thing, know ten thousand things."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width