Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointer Arithmetic CSE 2541 Rong Shi. Pointer definition A variable whose value refers directly to (or "points to") another value stored elsewhere in.

Similar presentations


Presentation on theme: "Pointer Arithmetic CSE 2541 Rong Shi. Pointer definition A variable whose value refers directly to (or "points to") another value stored elsewhere in."— Presentation transcript:

1 Pointer Arithmetic CSE 2541 Rong Shi

2 Pointer definition A variable whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address Memory addresses – Z + – Positive, whole number Why do pointers have an associated type? Ex: – int *pfloat * pchar * p

3 From earlier material… intarray[10]; int*ap = array + 2; // ap points at &array[2] 1. ap 2.*ap 3.ap[0] 4.ap + 6 5.*ap + 6 6.*(ap + 6) 7.ap[6] 8.&ap 9.ap[-1] //ap[-3]? 10.ap[9]

4 Pointer arithmetic example int array[] = { 1, 2, 3 }; int *array_ptr = array; // try different types printf(“First: %i\n”, *(array_ptr++)); // printf(“First: %i\n”, *(++array_ptr)); printf(“Second: %i\n”, *(array_ptr++)); printf(“Third: %i\n”, *array_ptr);

5 Pointer arithmetic When you add to or subtract from a pointer, the amount by which you do that is multiplied by the size of the type the pointer points to. For the previous slide, each increment adds 1 times sizeof(int) – p++=>value of p = old value of p + 4

6 Examples

7 NULL vs 0 vs ‘\0’ NULL is a macro defined in several standard headers – Only used for pointers – May be defined as ((void *) 0) 0 is an integer constant – 0 acts as the generic symbol for every type’s zero value '\0' is a character constant – Referred to as nul – Only exists if you #define it yourself

8 NULL and void – ((void *) 0) 0 – the value of a NULL pointer (using casting) VOID – no type – Cannot use arithmetic on a void pointer (no sizeof) – Cannot dereference (no type to return / unable to determine how many bytes to consider) NULL is defined as 0 cast to a void * pointer(NOT an uninitialized pointer) Note that NULL and void are separate concepts char *p=0; char *t=NULL; int i=0; char *q=(char*)i; // char * not the same type/sizeof as int * char *q=0 char *q=(char*)0

9 L and R values L-value (appearing on the left side of an assignment) – A place (i.e. memory location) for a value to be stored R-value (appearing on the right side of an assignment) – A value or expression that simplifies to a value a = b+25 vs b+25 = a int a[30]; a[b+10]=0; int a, *pi; pi = &a; *pi = 20;

10 L and R values Given: char ch = ‘a’; char *cp = &ch;

11 Pointers to Arrays (* )[ ] Ex: a pointer ptr to an array of 5 integers. – int(*ptr)[5]; Ex: an array of 5 int pointers – int *ptr[5];


Download ppt "Pointer Arithmetic CSE 2541 Rong Shi. Pointer definition A variable whose value refers directly to (or "points to") another value stored elsewhere in."

Similar presentations


Ads by Google