【问题标题】:Error: Expected ‘struct tree_node *’ but argument is of type ‘struct tree_node *’错误:应为“struct tree_node *”,但参数的类型为“struct tree_node *”
【发布时间】:2020-12-20 23:16:18
【问题描述】:

我在尝试为结构的组件赋值时遇到两个错误,后来在将结构的指针传递给函数时遇到了两个错误。

我有一个用户定义的数据类型:my_node 在头文件中定义如下:

enum n_type
{
    N_COMMAND,
    N_PIPE,
    N_REDIRECT,
    N_SUBSHELL,
    N_SEQUENCE,
    N_DETACH
};


struct my_node;
typedef struct my_node node_t;

struct my_node
{
    enum n_type type;

    union {
        struct {
            char *program;
            char **argv;
            size_t argc;
        } command;

        struct {
            node_t **parts; // array
            size_t n_parts;
        } pipe;
        
        struct {
             ... etc
}

我有一个函数,它接受一个指向 my_node 变量的指针:

void run_command(struct my_node *a_node);

在 myprogram.c 中,我尝试创建一个新节点,填充其组件,定义指向其地址的指针,然后将指针传递给上面的函数,如下所示:

// first I get input as a string:
fgets(str, 100, stdin);

// create the new node
struct my_node
{
    enum n_type type; 
    union
    { 
    struct {
        char *program;
        char **argv;
        size_t argc;
        } command;
    };
} node;

// assign values to its components (values are just for testing)
node.type = N_COMMAND;
node.command.program = &str;
node.command.argv = &node.command.program;
node.command.argc = 3;

// define a pointer to the node
struct my_node *ptr;
ptr = &node;

//pass the pointer to run command to execute it 
run_command(ptr);

当我尝试编译时,我得到了那些奇怪的错误:

gcc ./shell.c -o shelli
./shell.c: In function ‘main’:
./shell.c:37:23: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
  node.command.program = &str;
                       ^
./shell.c:47:14: warning: **passing argument 1 of ‘run_command’ from incompatible pointer type** [-Wincompatible-pointer-types]
  run_command(ptr);
              ^~~
In file included from ./shell.c:2:0:
./shell.h:21:6: note: **expected ‘struct tree_node *’ but argument is of type ‘struct tree_node *’**
 void run_command(struct tree_node *n);
      ^~~~~~~~~~~

为什么提供的参数类型和请求的参数类型相同,但仍然有错误?

【问题讨论】:

  • 什么是struct tree_node?您从未定义它,但它显示在编译器的错误消息中。
  • 由于您没有显示重现问题的代码,我们无法帮助解决它。您很有可能在函数范围内重新定义 struct my_node,然后尝试将嵌套类型的变量传递给采用非嵌套类型的函数。这是根据在 struct my_node 定义之前对 fgets() 的调用判断的。请创建一个 MCVE(Minimal, Complete, Verifiable Example — 或 MRE 或 SO 现在使用的任何名称)或 SSCCE(Short, Self-Contained, Correct Example)。 ]

标签: c linux


【解决方案1】:

str 的类型是什么?我的猜测是它是char*,因为您将它用作fgets 的参数,并且编译器没有抱怨。如果是这样的话,那么

node.command.program = &str;

由于node.comand.program 的类型为char*,因此无法编译,但&str 的类型为char**。所以,解决办法就是去掉&,即。

node.command.program = str;

编译消息指示 struct tree_node 类型,但该类型未在您的问题中定义。我假设它类似于您的 struct node 定义。有了这个假设,run_command(ptr) 是一个问题,因为您重新定义了源文件中的 struct node 是什么。重新定义与头文件中的原始定义不兼容。您应该在头文件中只定义一次结构,然后将该头文件包含在使用该结构的任何源文件中。

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多