Week 4-5 - Pointers and Dynamic Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

CSE 121 – Advanced C Programming

Dr. Nawal El Boghdady


[email protected]

WEEKS 4-5: POINTERS AND DYNAMIC ARRAYS


Agenda
Pointer Variable Definitions and Initialization
Pointer Operators
Pointer Expressions and Pointer Arithmetic
Arrays vs Pointers
Arrays of Pointers
1D and Multidimensional Dynamic Arrays
Pointer Definition
Pointers
A pointer is the memory address of a variable
Pointers are declared as:
p
float* p;
?
This identifies p as a pointer variable of type “pointer to float”.
This stores the memory address of a float variable in p.
To access the contents real memory item with address 101, we use *p.
If we only refer to p, we are accessing the address of the memory block, and not the contents
of the memory block.
Pointers Tell
Where To Find A Variable
The ? in the memory cell pointed to by p indicates that its contents are undefined after
float* p; is executed.
How do I assign a value to the memory location pointed to by p?

*p = 15.5;

p
15.5
Passing by Reference vs Passing
by Value

Memory Address Variable Name

1000 20 x

1001

1002
Passing by Reference vs Passing
by Value

Memory Address Variable Name

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;

int *yPtr = &y;


The Indirection (*) Operator
•Also called the Dereferencing Operator; applied to get the value stored in the memory location to
which the pointer points.

printf("%d", *yPtr); //prints the value stored in ‘y’, which is 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 (--)

•adding an integer to a pointer (+ or +=)

•subtracting an integer from a pointer (- or -=)

•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

•In conventional arithmetic, 3000 + 2 yields


the value 3002. This is NOT the case with
pointer arithmetic.

•When you add an integer to or subtract one


from a pointer, the pointer increments or
decrements by that integer times the size of
the object to which the pointer refers.

•vPtr += 2; // This will increment the pointer


ADDRESS by TWO LOCATIONS!
Pointers vs Arrays
•You can think of an array name as a constant pointer to the array’s first element. Pointers can be used to do
any operation involving array subscripting.

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; //This is equivalent to the following:

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:

ptr = (cast-type*) malloc(byte-size)

Example:

ptr = (int*) malloc(100 * sizeof(int));

//Dynamically creates an array of size 100; each element of which


is an int.
Example
#include <stdio.h> }

#include <stdlib.h> else {

int main() printf("Memory successfully allocated using malloc.\n");

{ for (i = 0; i < n; ++i) {

int* ptr; ptr[i] = i + 1;

int n, i; }

printf("Enter number of elements:"); printf("The elements of the array are: ");

scanf("%d",&n); for (i = 0; i < n; ++i) {

printf("Entered number of elements: %d\n", n); printf("%d, ", ptr[i]);

ptr = (int*)malloc(n * sizeof(int)); }

if (ptr == NULL) { }

printf("Memory not allocated.\n"); return 0;

exit(0); }

You might also like