【问题标题】:Accessing Dynamic allocated element and array访问动态分配的元素和数组
【发布时间】:2017-02-28 02:13:33
【问题描述】:
typedef struct myArrays
{
int id;
}MyArray;

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

在数组分配的第一种情况下,myArray = malloc(10 * sizeof (myArray) ),myArray[i] 指向第 i 个元素。所以我们也在这里 在引用其成员时应使用箭头,例如 (myArray[i]->myVar)。

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

【问题讨论】:

  • 因为您没有分配指针数组。 myArray 的定义在哪里?请展示一个完整、有效的示例。
  • 我编辑了我的问题。
  • (*X).YX[0].Y 含义相同

标签: c arrays malloc dynamic-memory-allocation


【解决方案1】:

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

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;

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

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

2 后缀表达式后跟方括号 [] 中的表达式 是数组对象元素的下标名称。这 下标运算符 [] 的定义是 E1[E2] 等同于 (*((E1)+(E2)))。由于适用于 二进制 + 运算符,如果 E1 是一个数组对象(相当于一个指针 到数组对象的初始元素)并且 E2 是一个整数, E1[E2] 表示 E1 的第 E2 个元素(从零开始计数)。

这样你甚至可以写

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;
}

【讨论】:

  • 你甚至在最后添加了细微差别!如果你#define h ++ 那么你可以有一个h 0[a].x... :)
【解决方案2】:

我明白了。在数组的情况下:myArray[i].myVar 表示*(myArray + i).myVar,在元素情况下:myArray-&gt;myVar 也表示(*myArray).myVar。所以基本上我也可以使用“(*myArray).myVar”代替myArray-&gt;myVar。我也可以使用(myArray + i)-&gt;myVar 代替myArray[i].myVar

简介:

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

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

【讨论】:

  • 由于运算符的优先级 myArray[i].myVar 表示 ( *(myArray + I ) ).myVar 即你需要多使用一对括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2011-12-10
  • 2020-10-24
  • 2016-12-13
  • 2021-06-29
  • 2019-07-19
  • 2022-11-13
相关资源
最近更新 更多