Baez
Baez

Reputation: 3

Having trouble using Structures and Pointers in C

I am programming in C. Considering the following Code.

My structure is defined as:

// Define the stack
struct stackNode {
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;

The following Variables are used:

StackNode topTracker; // The pointer of this stackNode will always point to the top of the stack

And I am trying to complete the following function.

char pop( StackNodePtr *topPtr ){
    char returnable;
// store the Node.data from the top of the stack
    returnable = *topPtr.data; //[1]
// Set the next Node to the top of the stack
    topTracker.nextPtr = *topPtr.nextPtr; //[2]
// return the Node data.
    return returnable;

The problem is I get the following error: at Point [1] & [2] respectively

"request for member data' in something not a structure or union" "request for membernextPtr' in something not a structure or union"

How do I get around this error and actually access the data and nextPtr of the pointer *topPtr? Given that *topPtr will be a pointer to an actual StackNode at runtime.

Upvotes: 0

Views: 234

Answers (3)

alvin
alvin

Reputation: 1196

*topPtr gives a StackNodePtr. which is still one level away from the structure. you need to dereference it once again to get StackNode.
(**topPtr) will give the StackNode.

use (**topPtr).data or (*Ptr)->data to get to the structure member.

Upvotes: 1

Nik
Nik

Reputation: 695

u r using wrong syntax it shud be topPtr->data. Also if u need to learn, learn now about memory leaks. It is there in ur above program. so as soon as u retrieve ur data free the memory Eg. returnable = topPtr->data; StackNodePtr *tmp = topPtr; topTracker->nextPtr = topPtr->nextPtr; free(tmp); return returnable;

Upvotes: -1

Oswald
Oswald

Reputation: 31637

topPtr is of type StackNodePtr* which is an alias for StackNode**. This means that *topPtr is of type StackNode* which is a pointer type and you must access the members using ->.

Also beware that the operators . and -> bind stronger than unary *. You therefore have to use parenthesis to manipulate the evaluation order:

returnable = (*topPtr)->data;

or

returnable = (**topPtr).data;

Upvotes: 3

Related Questions