Reputation: 1455
I'm confused on how to use pointer notation to access a struct used with malloc. I can use array notation but what's the syntax on pointer?
#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);
}
Upvotes: 1
Views: 2159
Reputation: 4594
Basically x->y
is shorthand for (*x).y
.
The following are equivalent:
(planes + 5) -> altitude = 9
and
(*(planes + 5)).altitude = 9;
and
planes[5].altitude = 9;
A more concrete example:
Flight my_flight; // Stack-allocated
my_flight.altitude = 9;
Flight* my_flight = (Flight*) malloc(sizeof(Flight)); // Heap-allocated
my_flight->altitude = 9;
Upvotes: 2
Reputation: 5154
You need an extra parenthesis after dereferencing the pointer.
(*(planes + 5)).altitude = 9;
Upvotes: 0
Reputation: 40211
You don't need the ->
notation for this, because you are already dereferencing the pointer using the asterisk. Simply do:
*(places + 5).altitude = 5;
The ->
is shorthand for "dereference this struct pointer and access that field", or:
(*myStructPointer).field = value;
is the same as
myStructPointer->field = value;
You can use either notation, but (should) not both at the same time.
Upvotes: 1