访问动态分配的元素和数组

Accessing Dynamic allocated element and array

typedef struct myArrays
{
int id;
}MyArray;

当我们像这样分配动态数组时:MyArray * myArray = malloc(10 * sizeof (myArray) ); 然后我们像这样使用点(。)运算符访问内存位置:myArray[0].myVar,但是当我们创建单个元素时 MyArray * myArray = malloc( sizeof (myArray) );然后我们像这样 myArray->myVar 使用箭头 (->) 访问它的成员。

In first case of array allocation , myArray = malloc(10 * sizeof (myArray) ), myArray[i] is pointing to ith element. So here also we should use arrow while refering to its members like (myArray[i]->myVar).

我知道 (myArray[i]->myVar) 是错误的,但请从概念上解释为什么它是错误的?

正如你自己提到的,如果你有一个声明

struct A
{
    int x;
} *a = malloc( sizeof( struct A ) ); 

然后你可以这样写

a->x = 10;

( a + 0 )->x = 10;

相同
( *a ).x = 10;

( *( a + 0 ) ).x = 10;

一样
a[0].x = 10;

您可以将指向单个对象的指针视为指向仅包含一个元素的数组的第一个元素的指针。

如果你有一个像

这样的结构数组
struct A
{
    int x;
} *a = malloc( 10 * sizeof( struct A ) ); 

你可以这样写

int i = 5;

( a + i )->x = 10;

相同
( *( a + i ) ).x = 10;

一样
a[i].x = 10;

带下标运算符的后缀表达式returns指向对象的左值。

来自 C 标准(6.5.2.1 数组下标)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

这样你甚至可以写

0[a].x = 10;

例如

#include <stdio.h>
#include <stdlib.h>

int main( void ) 
{
    struct A
    {
        int x;
    } *a = malloc( sizeof( struct A ) ); 

    0[a].x = 10;

    printf( "a->x = %d\n", a->x );

    free( a );

    return 0;
}

我得到了数组的 reason.In 大小写:myArray[i].myVar 表示 *(myArray + i).myVar 并且在元素大小写中:myArray->myVar 也表示 (*myArray).myVar。所以基本上我也可以用“(*myArray).myVar”代替myArray->myVar。我也可以用 (myArray + i)->myVar 代替 myArray[i].myVar.

简而言之:

myArray[i].myVar == (*(myArray + i)).myVar == (myArray + i)->myVar

myArray->myVar == (*myArray).myVar