Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointers & Arrays.

Similar presentations


Presentation on theme: "Pointers & Arrays."— Presentation transcript:

1 Pointers & Arrays

2 Pointer Arithmetic Some weirdness:

3 Pointer Arithmetic Adding 1 to pointer moves it one element: 0x116
Address Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 0x110 0x109 0x108 0x107 x 5 0x106 0x105 0x104 0x103 p 0x102 0x101 0x100

4 Pointer Arithmetic Adding 1 to pointer moves it one element: 0x116
Address Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 0x110 0x109 0x108 0x107 x 5 0x106 0x105 0x104 0x103 p 0x102 0x101 0x100

5 Pointer Arithmetic Adding 1 to pointer moves it one element: 0x116
Address Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 x 2.5 0x110 0x109 0x108 0x107 0x106 0x105 0x104 0x103 p 0x102 0x101 0x100

6 Pointer Arithmetic Adding 1 to pointer moves it one element:
Size of element determines size of move Address Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 x 2.5 0x110 0x109 0x108 0x107 0x106 0x105 0x104 0x103 p 0x102 0x101 0x100

7 Arrays Arrays stored as base address int quiz[3]; quiz : 0x100 0x116
Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 quiz[2] 8 0x110 0x109 0x108 0x107 quiz[1] 5 0x106 0x105 0x104 0x103 quiz[0] 10 0x102 0x101 0x100

8 Arrays Subscript indicates elements to skip forward
cout << quiz[2]; quiz[2] quiz + 2 ints 0x = 0x108 Address Identifier Value 0x116 0x115 0x114 0x113 0x112 0x111 quiz[2] 8 0x110 0x109 0x108 0x107 quiz[1] 5 0x106 0x105 0x104 0x103 quiz[0] 10 0x102 0x101 0x100

9 Arrays almost = Pointers
Array : base address of contiguous list of one type of data Pointer : memory address for one type of data

10 Access Array Can access array as pointer
Pointer arithmetic to get other elements int nums[3] = {5,6,7}; cout << *nums << endl; cout << *(nums + 1) << endl; cout << *(nums + 2) << endl;

11 Access Pointer Can use subscript on pointer
Accessing elements after first may not be smart

12 Arrays almost = Pointers
Anywhere you need an array you can use a pointer:

13 Error Why this message talks about int*

14 Returning a New array Can't return array from function:
But can return pointer to where array starts:

15 Returning a New array Function to return new array containing even numbers:


Download ppt "Pointers & Arrays."

Similar presentations


Ads by Google