Slides - Rose

Intro to Pointers in C
CSSE 332
Operating Systems
Rose-Hulman Institute of Technology
Announcements
• Homework 1 is due Monday at 11:59 PM
• Lab 1 due Tuesday at 11:59 PM
• Run svn st at a terminal to check the status
of your repo.
• Have you committed changes you have
made?
• Have you added your new files to your
repo?
Memory layout and addresses
int x = 5, y = 10;
float f = 12.5, g = 9.8;
char c = ‘r’, d = ‘s’;
x
5
4300
y
f
10
4304
g
12.5
4308
9. 8
4312
c
d
r
s
4316 4317
Pointers made easy
float f;
// variable that stores a float
float *f_addr; // pointer variable that stores the address of a float
f
f_addr
?
?
4300
4304
f_addr = &f;
f
// & = address operator
f_addr
?
4300
4300
4304
NULL
Dereferencing a pointer
*f_addr = 3.2;
f
// indirection or dereferencing operator
g
f_addr
3.2
4300
3.2
4300
4304
4308
float g=*f_addr; // indirection: g is now 3.2
f = 1.3;
f
f_addr
1.3
4300
4300
4304
Pointer operations
Creation
int iVal, value = 8, *ptr, *iPtr;
●
ptr = &value; // pointer assignment & initialization
●
iPtr = ptr;
●
●
Pointer indirection or dereferencing
●
iVal = *ptr;
●
*ptr is the int value pointed to by ptr
Pointer example, example 10
#include <stdio.h>
int main(int argc, char *argv[]) {
int j;
int *ptr;
/* initialize ptr before using it
*ptr=4 does NOT initialize ptr */
ptr=&j;
*ptr=4;
j=*ptr+1;
return 0;
}
/* j = 4 */
/* j = ? */
Pointers and arrays
int p[10], *ptr;
// Although p represents an array,
// both p and ptr are pointers,
// i.e., can hold addresses.
// p is already pointing to a fixed location and
// cannot be changed.
// ptr is still to be initialized.
p[i] is an int value
p, &p[i] and (p+i) are addresses or pointers
*p is the same as p[0]
(They are both int values)
*(p+i) is the same as p[i] (They are both int values)
How arrays and pointers
relate
int p[10];
p:
p[0]p[1]
See below instead
p[9]
int *pa;
pa = &p[0]; // same as pa = p;
pa:
pa + 5:
pa + 1:
p:
p[0]p[1]
p[9]
Pointer arithmetic
ptr = p;
ptr +=2;
// or ptr = &p[0]
// advances ptr to point to the second integer
// that follows where it currently points.
=> ptr = &(p[2]);
p = ptr; Gives error because “p” is a
constant address, points to the beginning of
an array and cannot be changed.
Summary of arrays and
pointers
• In C there is a strong relationship between
arrays and pointers
• Any operation that can be achieved by
array subscripting can be done with
pointers
• The pointer version will be faster, in
general
• A bit harder to understand
Enjoy Binkey and have fun
with *
http://cslibrary.stanford.edu/104/