1

我对如何使用指针表示法访问与 malloc 一起使用的结构感到困惑。我可以使用数组表示法,但指针的语法是什么?

  #include "stdio.h"
#include "stdlib.h"

using namespace std;

typedef struct flightType  {

    int altitude;
    int longitude;
    int latitude;
    int heading;

    double airSpeed;

} Flight;

int main() {

    int airbornePlanes;
    Flight *planes;

    printf("How many planes are int he air?");
    scanf("%d", &airbornePlanes);

    planes =  (Flight *) malloc ( airbornePlanes * sizeof(Flight));
    planes[0].altitude = 7;  // plane 0 works

    // how do i accessw ith pointer notation
    //*(planes + 1)->altitude = 8; // not working
    *(planes + 5) -> altitude = 9;
    free(planes);

}
4

3 回答 3

2

基本上x->y(*x).y.

以下是等价的:

(planes + 5) -> altitude = 9

(*(planes + 5)).altitude = 9;

planes[5].altitude = 9;

一个更具体的例子:

Flight my_flight; // Stack-allocated
my_flight.altitude = 9;

Flight* my_flight = (Flight*) malloc(sizeof(Flight)); // Heap-allocated
my_flight->altitude = 9;
于 2012-10-23T16:54:30.890 回答
1

您不需要此->符号,因为您已经使用星号取消引用指针。只需这样做:

*(places + 5).altitude = 5;

->是“取消引用此结构指针并访问该字段”的简写,或者:

(*myStructPointer).field = value;

是相同的

myStructPointer->field = value;

您可以使用任何一种表示法,但(应该)不能同时使用两种表示法。

于 2012-10-23T16:54:37.003 回答
0

取消引用指针后,您需要一个额外的括号。

(*(planes + 5)).altitude = 9;
于 2012-10-23T17:06:40.923 回答