Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the client can't dereference the pointer in this situation?

Tags:

c

pointers

struct

I understand the client can manipulate the pointer to the structure in this situation, but can't dereference it. I was wondering why exactly it can't be dereferenced?

stack.h

#ifndef STACK_INCLUDED
#define STACK_INCLUDED

typedef struct Stack_T *Stack_T;

extern Stack_T stack_new(void);
extern int stack_empty( Stack_T p_stk );
extern void stack_push( Stack_T p_stk, void *p_data );
extern void *stack_pop( Stack_T p_stk );
extern void stack_free( Stack_T *p_stk );

#endif

stack.c

#include "stack.h"

struct Stack_T {
    int node_count;
    struct node {
        void *p_data;
        struct elem *p_link;
    } *p_head;
};

main.c

#include "stack.h"

int main(void)
{
    Stack_T stk;
    ...
    return EXIT_SUCCESS;
}

To be more exact, why that object can't be dereferenced in main

like image 580
anacy Avatar asked Dec 02 '25 09:12

anacy


1 Answers

I assume by "client" you mean "a source file that includes stack.h".

The reason is that struct Stack_T is not actually defined in the stack.h file. It's declared, the typedef makes sure that the compiler understands that there is going to be a struct Stack_T defined somewhere, but not yet.

The stack.c is the only module that needs to know what is inside a struct Stack_T, so the definition of the structure is inside that file.

Clients of this code don't need to know what is inside a struct Stack_T, so they don't see the definition.

like image 123
Greg Hewgill Avatar answered Dec 05 '25 00:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!