Skip to content

Instantly share code, notes, and snippets.

@daniel-packard
Created April 11, 2016 21:05
Show Gist options
  • Save daniel-packard/d6e09d9d61886f02a7f42e0df81f18f3 to your computer and use it in GitHub Desktop.
Save daniel-packard/d6e09d9d61886f02a7f42e0df81f18f3 to your computer and use it in GitHub Desktop.
// compile with
// gcc pointers.c
#include <stdio.h>
typedef struct {
int x;
int y;
} point_t;
void printPointXY(int x, int y) {
printf("The point is: {%d, %d}\n", x, y);
}
int main(int argc, char* argv[]) {
// create a point
point_t X = {10, 15};
// create a pointer to that point!
point_t* pX = &X;
// there are a few (roughly equivalent) ways to access the point values through that pointer
// 1. de-reference that shit into a point, then access as you would normally (with a .)
// 2. de-reference in line with parentheses, then access as you would normally (with a .)
// 3. stabby arrow of syntactic sugar (equivalent... but like... way cooler looking)
// a couple of vars to read out the values of the point's x & y into
int x, y;
// 1.
// de-reference the pointer into a normal point.
point_t X2 = *pX;
// then access the fields like a normal struct
x = X2.x;
y = X2.y;
printPointXY(x,y);
// 2.
// de-refence the pointer in-line, and access the fields
x = (*pX).x;
y = (*pX).y;
printPointXY(x,y);
// 3.
// syntactic sugar ( -> de-references the pointer, AND accesses the field)
x = pX->x;
y = pX->y;
printPointXY(x,y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment