【问题标题】:C Code compiled failed in Linux Debian在 Linux Debian 中编译的 C 代码失败
【发布时间】:2014-06-19 03:56:37
【问题描述】:

我目前正在编写 C 程序,我在函数中使用结构和指针。一切都在 Windows 中运行良好,但不是 linux debian。当我尝试在 Linux Debian 中编译我的程序时遇到了一些错误。

typedef struct human
{
char name[100],code[100];
}human;

void hello(char* name, char* code)
{}

int main()
{
human human;
hello(&human.name,&human.code);
return 0; 
}

我在编译 main.c 文件时收到这些警告:

Warning passing argument 1 of Human from incompatible pointer type
Note: expected char *a but argument is type of char(*)[100]
Warning passing argument 2 of Human from incompatible pointer type
Note: expected char *a but argument is type of char(*)[100]

【问题讨论】:

    标签: c linux pointers struct


    【解决方案1】:
    typedef struct human
    {
        char name[100], code[100];
    } human;
    
    void hello(char* name, char* code)
    {
    }
    
    int main()
    {
        human human;
        hello(human.name, human.code);
        return 0; 
    }
    

    在传递 namecode 数组时删除与号 (&)。 char 数组与 char* 兼容。当您说human.name 时,您实际上指的是数组中第一个元素的地址。

    另外,如果hello 没有返回任何东西,它的返回类型应该是void。如果省略返回类型,则假定为 int,但这是一种非常古老的做法,非常不鼓励使用。

    在使用 GCC 编译时,您应该始终至少使用 -Wall。最佳做法(您应该尽早习惯)是:

    gcc -Wall -Wextra -Werror foo.c
    

    最后,使用适当的缩进!

    【讨论】:

      【解决方案2】:

      该错误基本上意味着您将数组的地址传递给需要char 数组的函数。

      human.name 的类型是 char [100],即大小为 100 的 char 数组。当您将其作为 human.name 传递给函数时,它会衰减为类型为 char* 的该数组的基地址。所以,一切都很好,你实际上只想要这种行为。

      现在,您尝试传递&human.name,这意味着您正在尝试将human.name 数组的地址传递给char (*) [100] 类型的函数(指向char 大小为100 的数组的指针),因此会发生类型不匹配。

      【讨论】:

        猜你喜欢
        • 2011-01-22
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        相关资源
        最近更新 更多