1 / 7

Pointers Quick Start Without the fluff

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

zubeda
Download Presentation

Pointers Quick Start Without the fluff

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pointers Quick StartWithout the fluff Pointers are variables that point to other variables. Think of them as aliases.

  2. 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”

  3. 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

  4. 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.

  5. 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

  6. 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

  7. 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

More Related