【发布时间】: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)。 ]