我在头文件中定义了一个用户定义的数据类型: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);// 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);
^~~~~~~~~~~为什么提供的参数类型和请求的参数类型相同,但仍然存在错误?
发布于 2020-12-21 10:07:48
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是什么。重新定义与头文件中的原始定义不兼容。只应在头文件中定义一次结构,然后将该头文件包含在使用该结构的任何源文件中。
https://stackoverflow.com/questions/65385761
复制相似问题