Search code examples
cstructstackc-stringsfunction-definition

Inserting string into stack returns random character


Working on pushing a string onto my stack and currently I am getting random characters ( the characters are not getting pushed on the stack because when I check afterwards my stack is empty)

here are the relevant functions and structure

typedef char stackitem;

struct stack {
stackitem  d;
struct stack *next;
};

typedef  struct stack ELEMENT;
typedef  ELEMENT   *POINTER;

void push(POINTER *Top, stackitem a)
/* Put item a into the top of the stack */
     {
        POINTER temp;
        temp = malloc(sizeof(ELEMENT));
        temp->d = a;
        temp->next = *Top;
        *Top = temp;
        printf("Insert element %c\n", temp->d);
     }
void push_string(POINTER *Top,char *string)
/* Push a string of characters into a stack. */
    {
        char *tmp = malloc(strlen(string) + 1);
        if (tmp)
        strcpy(tmp, string);
    push(&Top,tmp);

Parts of the second function I found on another SO thread. And this is how I am using it:

main()
    {
    POINTER top;
        top= (POINTER) NULL;
        stackitem A='A';
        stackitem B='B';
        char *C="12345";
        push_string(&top,C);
        print_stack(top);

        return 0;
   }
      

How am i able to add a string to the stack? the push function works for pushing chars onto the stack but I cant get it to push a whole string.


Solution

  • Firstly, turn on all warning (options -Wall -pedantic). The compiler will likely complain about the casting between non-compatible types.

    The function push() is dedicated to put a single char on the stack, whereas push_string() is dedicated to put all characters of string one by one.

    Therefore to put a string you should put each character of the string individually.

    void push_string(POINTER *Top,char *string) {
      for (char *s = string; *s; ++s)
        push(Top, *s);
    }