使用指针时不兼容的类型

#include  #include  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]); 

更改

 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]); 

应该

  print_contact(&contacts.data[i]); 

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

请注意: my_string未在代码中定义,标准标头不包含它。

你错过了一个参考:

  print_contact(&contacts.data[i]);