【问题标题】:incompatible type when using pointers使用指针时不兼容的类型
【发布时间】:2015-06-02 08:31:32
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

typedef struct contact
{
    my_string name;
    my_string email;
    int age;
} contact;

typedef struct contact_array
{
    int size;
    contact *data;
} contact_array;

void print_contact(contact *to_print)
{
    printf("%s (%s) age %i\n", to_print->name.str, 
    to_print->email.str, to_print->age);
}

int main()
{
    int i;
    contact_array contacts = { 0, NULL };
    for(i = 0; i < contacts.size; i++)
    {
        print_contact(contacts.data[i]);
    }

    return 0;
}

我收到以下错误:

error: incompatible type for argument 1 of 'print_contact'
note: expected 'struct contact *' but argument is of type 'contact'.

我已经在别处声明了my_string 结构,我认为这不是问题所在。我只是不确定如何让打印过程调用和过程声明具有匹配的类型。

【问题讨论】:

  • 将 void print_contact(contact *to_print) 更改为 void print_contact(contact to_print)。您正在传递的 contacts.data[i] 不是地址,而是数据块本身
  • @Lewis,如果您只是要打印值,则不需要通过引用传递。只需将void print_contact(contact *to_print) 更改为void print_contact(contact to_print)

标签: c pointers incompatibletypeerror


【解决方案1】:

您的编译器告诉您将指针类型传递给print_contact 函数,如下所示:

print_contact(&contacts.data[i]);

【讨论】:

  • 非常感谢,这是这个解决方案的组合,加上我尝试了一个不同的用户输入库,似乎能够使用你推荐的更改。
【解决方案2】:

改变

void print_contact(contact *to_print)

void print_contact(contact to_print)

或将其传递为

print_contact(&contacts.data[i]);

您传递的不是地址而是数据块本身的contacts.data[i]

【讨论】:

    【解决方案3】:
        print_contact(contacts.data[i]);
    

    应该是

        print_contact(&contacts.data[i]);
    

    这是因为contacts.data 的类型为struct contact *,而contacts.data[i] 的类型为struct contact。因此,您可以通过 contacts.data + i&amp;contacts.data[i] 。只是符号上的区别。

    注意:my_string 没有在代码中定义,标准头也不包含它。

    【讨论】:

    • OP 已经提到 my_string 在别处定义。
    • 是的,它被提到了,但是代码上似乎没有包含它的头文件,因此我提到了它。
    【解决方案4】:

    您缺少参考:

        print_contact(&contacts.data[i]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多