Pointers In C

  • November 2019
  • 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 Pointers In C as PDF for free.

More details

  • Words: 732
  • Pages: 16
C++ Pointers and C Strings

CS1 - Pointers

1

Pointers A pointer is a variable that holds the address of something else. int foo; foo int *x;

0 1 2 3 4 5

123

x

81345 81346 81347

CS1 - Pointers

...

...

foo = 123; x = &foo;

Address

MEMORY

3 2

int *x; • x is a pointer to an integer. • You can use the integer x-points-to in a C++ expression like this: “the int x points to” y = *x + 17;

*x = *x +1; CS1 - Pointers

3

&foo In C++ you can get the address of a variable with the “&” operator. int foo; foo = 123; x = &foo;

Address

0 1 2 foo 3 4 5

...

CS1 - Pointers

123 ...

&foo means “the address of foo”

MEMORY

4

Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; !! ! R o O ERR n’t point t s x doe

!! ! g n i anyth

int foo; int *x; x = &foo; *x=3; ne i f s i oo f this o t ts n i o p x

CS1 - Pointers

5

Pointers to anything x

int *x; int **y;

double *z;

y

some *int

z

CS1 - Pointers

some int

some int

some double

6

Pointers and Arrays • An array name is basically a const pointer. • You can use the [] operator with a pointer: x is “the address of a[2] ” int *x; int a[10]; x = &a[2]; for (int i=0;i<3;i++) x[i]++; x[i] is the same as a[i+2] CS1 - Pointers

7

Pointer arithmetic • Integer math operations can be used with pointers. • If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a;

*(ptr+2)

*ptr a[0]

a[1]

a[2]

a[3]

*(ptr+4)

a[4]

int a[5]; CS1 - Pointers

8

printing an array void print_array(int a[], int len) { for (int i=0;i
Pointers In C
November 2019 17
Pointers In C++
June 2020 6
Pointers
November 2019 36
Pointers
May 2020 9