Week 4-5 - Pointers and Dynamic Arrays
Week 4-5 - Pointers and Dynamic Arrays
Week 4-5 - Pointers and Dynamic Arrays
*p = 15.5;
p
15.5
Passing by Reference vs Passing
by Value
1000 20 x
1001
1002
Passing by Reference vs Passing
by Value
1000 20 x
1001
1002
Initializing Pointers
Pointers can either be initialized to:
• An address: the address of another cell in memory
• NULL: Pointer points to nothing. We will see why this is important when we talk about Linked Lists.
• 0: If you want your pointer to point to nothing, you can also set it to 0, however, this is confusing and NULL
should be used instead.
Pointer Operators
The Address(&) Operator
•Using the address operator(&) returns the address of the pointer
int y = 5;
printf("%d", yPtr); //prints the value stored in ‘yPtr’, which is the address of ‘y’ -> 600000
Example
aPtr a
0x7fffe69 0x7fffe69386cc
0x7fffe69 7
386cc 386cc
Example 2
// Converting a string to uppercase using a
// non-constant pointer to non-constant data. // convert string to uppercase letters
#include <ctype.h> void convertToUppercase(char *sPtr) {
#include <stdio.h> while (*sPtr != '\0') { // current character
is not '\0'
void convertToUppercase(char *sPtr); // prototype *sPtr = toupper(*sPtr); // convert to
uppercase
int main(void) { ++sPtr; // make sPtr point to the next
char string[] = "cHaRaCters and $32.98"; // character
initialize char array }
}
printf("The string before conversion is:
%s\n", string);
convertToUppercase(string);
printf("The string after conversion is: %s\n",
string);
}
Pointer Arithmetic
Pointer Arithmetic Operators
•incrementing (++) or decrementing (--)
•subtracting one pointer from another—meaningful only when both pointers point into the same array.
Aiming a Pointer at an Array
The variable vPtr can be initialized to point to array v with either of the statements:
vPtr = v;
vPtr = &v[0];
Adding/Subtracting an Int to a
Pointer
int b[5];
int *bPtr;
•Array b is a pointer to the array’s first element, we can set bPtr to the address of the array b’s first element:
bPtr = &b[0];
Example
Multidimensional
Arrays
2D Arrays: Card Shuffling and
Dealing
We use a 4-by-13 two-dimensional array deck to represent the deck of playing cards:
Shuffling 2D Arrays: Card Deck
Algorithm:
1. Set all elements to 0.
2. Choose a row (0–3) and a column (0–12) at random. Place the number 1 in array element
deck[row][column] to indicate that this card will be the first one dealt from the shuffled deck.
3. Repeat this process for the numbers 2, 3, …, 52, randomly inserting each in the deck array to the order
of the cards in the shuffled deck.
4. Only deck[row][column] elements containing a non-zero value should be considered. Otherwise, skip it.
5. Eventually, the numbers 1 through 52 will occupy the deck array’s 52 slots.
6. Return the shuffled deck of cards.
Example
Output
Dynamic Arrays
malloc for Dynamically creating
an array of size n
Syntax:
Example:
int n, i; }
if (ptr == NULL) { }
exit(0); }