简体   繁体   English

将结构指针传递给C中的函数

[英]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')" 我无法将结构传递给以结构指针作为参数的函数,并不断收到错误“错误:一元'*'(具有'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调用push(*stack, 'a')

push(&stack, 'a');
     ^

Indirection on stack ( * ) makes no sense since it's not a pointer. stack间接stack* )没有意义,因为它不是指针。 Taking its address ( & ) does. 取其地址( & )。

Since StackNodePtr is already a pointer to StackNode you don't need more '*' in argument list. 由于StackNodePtr已经是指向StackNode的指针,因此在参数列表中不需要更多的“ *”。

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. 它知道空指针(NULL)与StackNodePtr是不同的东西。 You need a cast on the call or a definition of a null stacknode pointer value. 您需要对调用进行强制类型转换,或者对null的stacknode指针值进行定义。

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. push和pop的定义是错误的,您给它一个stacknodeptr,但是希望有一个stacknodeptr指针。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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