Arrays And Pointers (1d Arrays)

  • April 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Arrays And Pointers (1d Arrays) as PDF for free.

More details

  • Words: 416
  • Pages: 2
C++ Notes: Arrays as Pointers Using an array name as a pointer An array name is really a pointer to the first element of the array. For example, the following is legal. int b[100];

// b is an array of 100 ints.

int* p;

// p is a pointer to an int.

p = b;

// Assigns the address of first element of b to p.

p = &b[0];

// Exactly the same assignment as above.

Array name is a const pointer When you declare an array, the name is a pointer, which cannot be altered. In the previous example, you could never make this assignment. p = b; b = p; type.

// Legal -- p is not a constant. // ILLEGAL because b is a constant, although the correct

Pointer arithmetic "Meaningful" arithmetic operations are allowed on pointers. • Add or subtract integers to/from a pointer. The result is a pointer. • Subtract two pointers to the same type. The result is an int. • Multiplying, adding two pointers, etc. don't make sense.

Pointer addition and element size When you add an integer to a pointer, the integer is multiplied by the element size of the type that the pointer points to. // Assume sizeof(int) is 4. int b[100];

// b is an array of 100 ints.

int* p;

// p is a a pointer to an int.

p = b;

// Assigns address of first element of b. Ie, &b[0]

p = p + 1;

// Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

Equivalence of subscription and dereference Because of the way C/C++ uses pointers and arrays, you can reference an array element either by subscription or * (the unary dereference operator). int b[100];

// b is an array of 100 ints.

int* p;

// p is a a pointer to an int.

p = b;

// Assigns address of first element of b. Ie, &b[0]

*p = 14;

// Same as b[0] = 14

p = p + 1;

// Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

*p = 22;

// Same as b[1] = 22;

Example - Two ways to add numbers in an array The first uses subscripts, the second pointers. They are equivalent. int a[100];

int a[100];

. . .

. . .

int sum = 0;

int sum = 0;

for (int i=0; i<100; i++) {

for (int* p=a; p
sum += a[i]; }

sum += *p; }

Related Documents

Arrays
November 2019 37
Arrays
May 2020 23
Arrays
November 2019 37
Arrays
November 2019 39
Arrays
November 2019 46