130 likes | 392 Views
Pointer Arithmetic. CSE 2541 Rong Shi. 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:
E N D
Pointer Arithmetic CSE 2541 Rong Shi
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 *p float * p char * p
From earlier material… int array[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]
Pointer arithmetic example intarray[] = { 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);
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
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
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
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 inta[30]; a[b+10]=0; inta, *pi; pi = &a; *pi = 20;
L and R values Given: char ch = ‘a’; char *cp = &ch;
Pointers to Arrays • <data type> (*<name of ptr>)[<an integer>] • Ex: a pointer ptr to an array of 5 integers. • int(*ptr)[5]; • Ex: an array of 5 int pointers • int*ptr[5];