gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:49:33 24 4
gpt4 key购买 nike

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;

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

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

关于c - 访问动态分配的元素和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42498959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com