C语言 -> C 结构的无效类型参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4983010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:46:06  来源:igfitidea点击:

Invalid type argument of -> C structs

cpointers

提问by system

I am trying to access items in an array of structs and print the structs fields as follows

我正在尝试访问结构数组中的项目并按如下方式打印结构字段

printList(Album *a, int numOfStructs)
{
    int i;
    int j;

    for(i = 0; i < numOfStructs; i++)
    {
         printf("number%d\n:", i+1);
         printf("%s", a[i]->field2);
         printf("%s", a[i]->field2);
         printf("%d", a[i]->field3);

         for(j = 0; j < a[i]->numOfStrings; j++)
         {
             printf("%s", a[i]->strings[j]);
         }
         printf("\n");
    }
}

but I get loads of errors as such

但我收到了很多错误

invalid type argument of '->'

“->”的无效类型参数

What am I doing wrong with this pointer?

我用这个指针做错了什么?

回答by James McNellis

ais of type Album*which means that a[i]is of type Album(it is the ith element in the array of Albumobject pointed to by a).

ais of typeAlbum*这意味着它a[i]的类型Album(它是指向iAlbum对象数组中的第 th 个元素a)。

The left operand of ->must be a pointer; the .operator is used if it is not a pointer.

的左操作数->必须是指针;该.运营商使用,如果它不是一个指针。

回答by J?rgen Sigvardsson

You need to use the .operator. You see, when you apply a *to a pointer, you are dereferencing it. The same goes with the []. The difference between *and []is that the brackets require an offset from the pointer, which is added to the address in the pointer, before it is dereferenced. Basically, these expressions are identical:

您需要使用.运算符。你看,当你*对一个指针应用 a 时,你是在取消引用它。同理[]*和之间的区别在于[]括号需要指针的偏移量,在取消引用之前,该偏移量被添加到指针中的地址。基本上,这些表达式是相同的:

*ptr == ptr[0]
*(ptr + 1) == ptr[1]
*(ptr + 2) == ptr[2]

To connect to your question: Change a[i]->field2and a[i]->field3to a[i].field2and a[i].field3.

要连接到你的问题:变革a[i]->field2a[i]->field3a[i].field2a[i].field3