CS157

CS157: Intro to C, Part II

Spring 2018

Pointers

See this page as a slide show

Pointers

CS157 Pointers

The best (and worst) thing about C

Best?

Worst?

What is a →pointer←, anyway?

Declaring and Initializing

Declare and initialize in one step: int *p = &x;

-or-

  1. Declare: int *p;
  2. Initialize: p = &x;

Yeah, but what is a pointer?

int a = 123;
int *p = &a;

Physically, assuming a lives at location 7689:

      ┌────┐     ┌───┐
    p:│7689│   a:│123│
      └────┘     └───┘

Or, thinking the contents of p as a pointer rather than as a number:

      ┌──┐       ┌───┐
    p:│ ─┼────>a:│123│
      └──┘       └───┘

Yeah, but what is a pointer?

It’s a variable that points to another.

int val;    // regular int
int *ptr;   // pointer to an int


        ┌────┐        ┌────┐
    ptr:│ ?? │    val:│ ?? │
        └────┘        └────┘

Yeah, but what is a pointer?

It’s a variable that points to another.

int val;    // regular int
int *ptr;   // pointer to an int
ptr = &val; // ptr contains the address of val


        ┌──┐         ┌────┐
    ptr:│ ─┼────>val:│ ?? │
        └──┘         └────┘

Yeah, but what is a pointer?

It’s a variable that points to another.

int val;    // regular int
int *ptr;   // pointer to an int
ptr = &val; // ptr contains the address of val
*ptr = 42;  // Whatever ptr refers to becomes 42


        ┌──┐         ┌────┐
    ptr:│ ─┼────>val:│ 42 │
        └──┘         └────┘

Some Examples

      ┌──┐     ┌───┐      ┌──┐
      │ ─┼────>│123│<─────┼─ │
      └──┘     └───┘      └──┘
       p         x          q
int x, *p = &x, *q = &x;
x=4;           printf("x=%d\n", x);
x=x+3;         printf("x=%d\n", x);
*p = 42;       printf("x=%d\n", x);
*q = 8;        printf("x=%d\n", x);
*&x = *q + *p; printf("x=%d\n", x);
x = *q**p;     printf("x=%d\n", x);
x=4
x=7
x=42
x=8
x=16
x=256

And this is useful because …

What about this?

void swap(int *a, int *b);
int main() {
    int i=2, j=5;
    swap(&i, &j);
    return 0;
}


      ┌──┐       ┌───┐
    a:│ ─┼────>i:│ 2 │
      └──┘       └───┘
      ┌──┐       ┌───┐
    b:│ ─┼────>j:│ 5 │
      └──┘       └───┘

The swap routine

By using pointers we can make ONE more generic swap routine, using “Pass by reference” instead of “Pass by value”

void swap(int *a, int *b) {
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

When do we need Pointers?

NULL

Pointer Arithmetic

Pointer Arithmetic Example

int data[] = {11,22,33,44,55,66,77,88};
int *p;
p = data;     printf("%d\n", *p);
p += 4;       printf("%d\n", *p);
p--;          printf("%d\n", *p);
p = &data[2]; printf("%d\n", *p);
11
55
44
33

Subscripting

double a[] = {1.2, 3.4, 5.6, 7.8};
printf("%f\n", a[2]);
printf("%f\n", *(a+2));
printf("%f\n", *(2+a));
printf("%f\n", 2[a]);
5.600000
5.600000
5.600000
5.600000

Array Name is Address

double a[] = {1.2, 3.4, 5.6, 7.8};
double *p;
p = a;     printf("%f\n", *p);
p = &a[0]; printf("%f\n", *p);
1.200000
1.200000

Arrays are pointers

void p3chars(char *p) {
    printf("%c%c%c\n", *p, *(p+1), *(p+2));
}

int main() {
    char buf[] = "abcdefghij";
    p3chars(&buf[0]); // abc
    p3chars(&buf[2]); // cde
    p3chars(buf);     // abc
    return 0;
}
abc
cde
abc

Pointer/Array Notation Correspondence

    char word[100];
    char * wptr = word;  // or char* wptr;  or char *wptr;
wptrword&word[0]
(wptr+n)word+n&word[n]
*wptr*wordword[0]
*(wptr+n)*(word+n)word[n]

Strings

Strings are char arrays, but arrays are just pointers, so a string is just a pointer to char(s)

String functions

strcpy(char *dest, char *src)
copy a string from src to dest

strcat(char *dest, char *src)
copy src onto the end of dest

int strcasecmp(const char *s1, const char *s2)
compare s1 to s2, ignoring case

More String Functions

strncpy(char *dest, char *src, int max)
copy up to max chars from src to dest

strncat(char *dest, char *src, int max)
copy up to max chars from src onto the end of dest

int strncasecmp(const char *s1, const char *s2, int max)
compare up to max chars from s1 to s2, ignoring case

String functions

strchr(char *s, char c)
Returns a pointer to the first occurrence of the character c in the string s, or NULL if it isn’t there

strstr(char *haystack, char *needle)
Returns a pointer to the first occurrence of the string needle in the string haystack, or NULL if it isn’t there!
char *p = strchr("My dog has fleas", 'g');
char *q = strstr("My dog has fleas", "has");
printf("p=%s\n", p);
printf("q=%s\n", q);
p=g has fleas
q=has fleas

String Ambiguity

char *p = "abc", *q = "abc";
if (p == q)
    puts("Same");
else 
    puts("Different");

Returning values

Pointers can also be used to return multiple values, instead of just one.

void func(int *a, int *b, int *c) {
    *a = 1; *b = 4; *c = 9;
}

int main() {
    int number=6, thingy=7, value=8;
    func(&number, &thingy, &value);
    printf("%d %d %d\n", number, thingy, value);
    return 0;
}
1 4 9

Returning multiple values

A function that takes two numbers and returns the quotient and the remainder!

void  long_division(int *quotient_ptr, int *remainder_ptr,
                    int dividend, int  divisor) {
    *quotient_ptr = dividend / divisor;
    *remainder_ptr = dividend % divisor;
}

int main() {
    int quot, rem;
    long_division(&quot, &rem, 40, 3);
    printf("quotient is %d, remainder is %d\n", quot, rem);
    return 0;
}
quotient is 13, remainder is 1

PROBLEMS!

int miles, nums[25];
int *a = &45;         // invalid — attempt to take address of a value
int *b = &(miles+10); // invalid — attempt to take address of a value
int *c = &miles + 10; // semi-valid — 10 is added to address of miles
int *d = &nums;       // invalid — nums is an address, so no address of the address!
int *e = nums;        // valid

PROBLEM! faults

Don’t dereference a variable that is not a pointer!

int num = 7;
printf("%d", *num);
c.c: In function 'main':
c.c:2: error: invalid type argument of unary '*' (have 'int')

Fastest way to a crash:

int *p = NULL;
puts("Here we go!");
*p = 0;
SIGSEGV: Segmentation fault

Modified: 2017-12-19T11:20

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building