简体   繁体   中英

Passing a struct pointer to a function in C

I'm having trouble passing a struct to a function that takes a struct pointer as an argument and keep getting the error "error: invalid type argument of unary '*' (have 'StackNode')"

Here's the necessary portions of my code (not all of it):

#include <stdio.h>
#include <stdlib.h>

struct stackNode{
    char data;
    struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;

void convertToPostfix(char infix[], char postfix[]);
int isOperator(char c);
int precedence(char operator1, char operator2);
void push(StackNodePtr *topPtr, char value);
char pop(StackNodePtr *topPtr);
char stackTop(StackNodePtr topPtr);
int isEmpty(StackNodePtr topPtr);
void printStack(StackNodePtr topPtr);

int main(){
    convertToPostfix(NULL, NULL);
    return 0;
}

void convertToPostfix(char infix[], char postfix[]){
    StackNode stack = {'(', NULL};
    push(*stack, 'a');
    printStack(&stack);
}

void push(StackNodePtr* topPtr, char value){
    topPtr->nextPtr = NULL; //just temporary, not needed
    topPtr->data = value; //just temporary, not needed
}

Any help will be appreciated, Thanks

Change the push call, push(*stack, 'a') :

push(&stack, 'a');
     ^

Indirection on stack ( * ) makes no sense since it's not a pointer. Taking its address ( & ) does.

Since StackNodePtr is already a pointer to StackNode you don't need more '*' in argument list.

Replace all

void push(StackNodePtr* topPtr, char value){ // WRONG
                     ^^^

to

void push(StackNodePtr topPtr, char value){ // RIGHT
                     ^^^

I think your compiler is being clever. It knows that a void pointer (NULL) is not the same thing as a StackNodePtr. You need a cast on the call or a definition of a null stacknode pointer value.

NULLSNP=(StackNodePtr)NULL;

As another post said, the call to push is also wrong, it should be & not &.

push(&stack, 'a');

The definition of push and pop is wrong, you give it a stacknodeptr but expect a stacknodeptr pointer.

void push(StackNodePtr topPtr, char value)
char pop(StackNodePtr topPtr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM