Ashish Rawat
Ashish Rawat

Reputation: 3513

Is it possible to implement stack with only pointer to structure (no data type)?

Suppose I have the following structure

typedef struct _Stack {
   struct _Stack *next;
} Stack;

Note in above there is no data type for storage, only *next pointer to structure. So, my question is will it be possible that the following function is valid.

void stackPush(Stack **stackP, void *dataP) {
    Stack *data = (Stack*)dataP;

    data->next = *stackP;
    *stackP = data;
}

I saw this function in glib library in the file gtrashstack.c. But when I compiled above, I got a warning : In data->next : assignment from incompatible pointer type.

I know that, I can rewrite the structure with generic pointer. But I only want to know, why the above will not work?

Update: My mistake, here I write typedef struct _Stack but in my program, I missed _Stack.

Upvotes: 3

Views: 129

Answers (2)

Marian
Marian

Reputation: 7472

This function is valid. Probably it is used for different structures like:

 typedef struct my_Stack {
   struct my_Stack *next;
   sometype1 somename1;
   ...
   sometypen somenamen;
 } MyStack;

i.e. for the lists where the pointer to the next elem is placed as the first field of the structure. It is the same trick as when classes are built via simple inheritance in C++. For such a structure you can call:

x = malloc(sizeof(struct my_Stack));
x->somename1 = aaa; ...
stackPush(&mylist, x);

I am not sure if this style of programming is supported by the C standard. It's not a good style for novices. It is for developers who know what they are doing in C.

Upvotes: 2

Dabo
Dabo

Reputation: 2373

The answer is yes, it is possible to implement stack with only pointer to structure (no data type). See implementation of generic list or queue in c in Linux (don't know if it is implemented in windows also). See how it is implemented Linux Kernel Linked List Explained

Upvotes: 1

Related Questions