70 likes | 178 Views
Pointers Quick Start Without the fluff. Pointers are variables that point to other variables. Think of them as aliases. Simple pointers. int x; // a variable of type int int *px; // a pointer-type variable // of type pointer to int. X = 3; // put 3 in x
E N D
Pointers Quick StartWithout the fluff Pointers are variables that point to other variables. Think of them as aliases.
Simple pointers. int x; // a variable of type int int *px; // a pointer-type variable // of type pointer to int. X = 3; // put 3 in x px = &x; // make px point to x cout << x; cout << *px; // same as cout << x; px x 3 px = &x means “make px point to x” *px means “what x is pointing to”
Pointers and arrays. int a[4] = { 1, 2, 3, 4 }; int* pa; pa = a; // makes pa point to the array a cout << a[3]; cout << pa[3]; // same as cout << a[3]; The name as an array denotes a constant pointer to the beginning of the array. a pa can be made to point somewhere else. a can not. 1 2 3 4 pa
s ps x 1 y 2 Pointers and structs Typedef struct { int x; int y; } mystruct; mystruct s = { 1, 2 }; // x is 1, y is 2 mystruct* ps = &s; // make ps point to s cout << s.x; cout << ps->x; // same as cout << s.x; The ‘->’ operator is used to access struct elements through a pointer.
Pointers and dynamic memory Memory requested dynamically is returned through a pointer to the memory. 1 int* da = 0; da = new int[3]; // request memory // use memory da[0] = 0; da[1] = 1; da[2] = 2; … delete []da; // return memory to system // for recycling 2 3 Not valid da da da 0 ? ? ? 0 1 2 1 2 3
More Pointers and dynamic memory A slightly different syntax for a struct that contains a pointer to the struct being defined. struct mystruct { int data; mystruct* next; } data next Can point to a struct of type mystruct
Simple example of a linked list h ? struct mystruct { int data; mystruct* next; } … mystruct *h = new mystruct; mystruct *t = h; t->data = 1; t->next = 0; t->next = new mystruct; t = t->next; t->data = 2; t->next = 0; ? t 1 h 1 0 t 2 1 h 2 1 ? 3 ? t 3 h 1 2 4 4 t 0