首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:应为“struct tree_node *”,但参数的类型为“struct tree_node *”

错误:应为“struct tree_node *”,但参数的类型为“struct tree_node *”
EN

Stack Overflow用户
提问于 2020-12-21 07:16:19
回答 1查看 172关注 0票数 0

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

代码语言:javascript
复制
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变量的指针:

代码语言:javascript
复制
void run_command(struct my_node *a_node);

代码语言:javascript
复制
// 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);

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

代码语言:javascript
复制
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);
      ^~~~~~~~~~~

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

EN

回答 1

Stack Overflow用户

发布于 2020-12-21 10:07:48

str的类型是什么?我的猜测是它是一个char*,因为您将它用作fgets的参数,并且编译器没有出现任何错误。如果是这样,那么

代码语言:javascript
复制
node.command.program = &str;

不编译,因为node.comand.program的类型是char*,但&str的类型是char**。因此,解决方案是删除&,即。

代码语言:javascript
复制
node.command.program = str;

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65385761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档