CSSE 332
Functions, Pointers in C
Functions - why and how ?
If a problem is large
Passing arguments to
functions
Modularization – easier
– By value
to:
Returning values from
• code
functions
• debug
– By value
Code reuse
2
Functions – basic example
Example 9
#include <stdio.h>
/* function prototype at start of file */
int sum(int a, int b);
int main(int argc, char *argv[]){
int total = sum(4,5); /* call to the function */
printf(“The sum of 4 and 5 is %d\n”, total);
}
/* the function itself arguments passed by value*/
int sum(int a, int b){
return (a+b);
/* return by value */
}
3
Memory layout and addresses
int x = 5, y = 10;
float f = 12.5, g = 9.8;
char c = ‘r’, d = ‘s’;
x
y
5
4300
f
10
4304
12.5
4308
4312
g
c
d
9. 8
r
s
4316 4317
4
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
NULL
// & = address operator
f_addr
?
4300
4300
4304
5
Dereferencing a pointer
*f_addr = 3.2;
f
// indirection operator or dereferencing
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
6
Pointer operations
Creation
– int iVal, *ptr, *iPtr;
– ptr = &iVal; // pointer assignment/initialization
– iPtr = ptr;
Pointer
indirection or dereferencing
– iVal = *ptr;
*ptr is the int value pointed to by ptr
7
Pointer Example 10
#include <stdio.h>
int main(int argc, char *argv[]) {
int j;
int *ptr;
/* initialize ptr before using it */
ptr=&j;
/* *ptr=4 does NOT initialize ptr */
*ptr=4;
/* j = 4 */
j=*ptr+1;
/* j =
? */
return 0;
}
8
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)
9
How arrays and pointers relate
int a[10];
a:
a[0] a[1]
See below instead a[9]
int *pa;
pa = &a[0]; // same as pa = a;
pa:
pa + 5:
pa + 1:
a:
a[0] a[1]
a[9]
10
Pointer arithmetic
int p[10];
ptr = p;
ptr +=2;
// or ptr = &p[0]
// ptr = ptr + 2 * sizeof(int) = ptr+8 bytes
=> ptr = &(p[2]);
p = ptr; Gives ERROR because “p” is a
constant address, points to the beginning
of an array and cannot be changed.
11
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
12
Homework 4
Another exercise on C.
Available on class’s Angel page
– follow link from the schedule page
13
© Copyright 2026 Paperzz