使用指针时类型不兼容

incompatible type when using pointers

#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 结构,我认为这不是问题所在。我只是不确定如何让打印过程调用和过程声明具有匹配的类型。

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

print_contact(&contacts.data[i]);
    print_contact(contacts.data[i]);

应该是

    print_contact(&contacts.data[i]);

这是因为contacts.datastruct contact *类型,而contacts.data[i]struct contact类型。因此,您可以传递 contacts.data + i&contacts.data[i] 。只是符号上的差异。

注意:my_string在代码中没有定义,标准headers不包含

改变

void print_contact(contact *to_print)

void print_contact(contact to_print)

或将其传递为

print_contact(&contacts.data[i]);

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

您缺少参考:

    print_contact(&contacts.data[i]);