0

hello guys how properly push,pop,display a char array into another char array, when come to int i can do but in char array its to hard to analyze.. pls guy need some help. thnx in advance

2
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Narue
0

It depends on how you're storing the items of the stack. Personally, I would use an array of structures:

struct item {
    char a[ITEM_SIZE];
};

struct item stack[STACK_SIZE];
size_t top = 0;

With that setup, pushing and popping are a simple matter of copying the contained array:

void push(const char a[], size_t size)
{
    if (top >= STACK_SIZE)
        return;

    if (size > ITEM_SIZE)
        size = ITEM_SIZE;

    memcpy(stack[top++].a, a, size);
}

void pop(char dst[], size_t size)
{
    if (top == 0)
        return;

    if (size > ITEM_SIZE)
        size = ITEM_SIZE;

    memcpy(dst, stack[--top].a, size);
}
0

thnx narue, but can you show me how to exactly apply this code with simple input and output?

0
char a[ITEM_SIZE];

if (fgets(a, sizeof a, stdin) != NULL)
    push(a, sizeof a);

pop(a, sizeof a);
puts(a);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.