0% found this document useful (0 votes)
6 views

ARRAYS and Pointers IN C_1

Uploaded by

stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ARRAYS and Pointers IN C_1

Uploaded by

stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

ARRAYS IN C

Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
To create an array, define the data type (like int) and specify the name of the array followed
by square brackets [].
To insert values to it, use a comma-separated list inside curly braces, and make sure all values
are of the same data type:
int myNumbers[] = {25, 50, 75, 100};
We have now created a variable that holds an array of four integers.
Access the Elements of an Array
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

// Outputs 25
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf("%d", myNumbers[0]);

// Now outputs 33 instead of 25


Loop Through an Array
You can loop through the array elements with the for loop.
The following example outputs all elements in the myNumbers array:
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
Set Array Size
Another common way to create arrays, is to specify the size of the array, and add elements
later:
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the number of array elements in advance, in order
for the program to store enough memory.
You are not able to change the size of the array after creation.
Avoid Mixing Data Types
It is important to note that all elements in an array must be of the same data type.
This means you cannot mix different types of values, like integers and floating point
numbers, in the same array:
Example
int myArray[] = {25, 50, 75, 3.15, 5.99};
In the example above, the values 3.15 and 5.99 will be truncated to 3 and 5. In some cases it
might also result in an error, so it is important to always make sure that the elements in the
array are of the same type.
Get Array Size or Length
To get the size of an array, you can use the sizeof operator:
Example
int myNumbers[] = {10, 25, 50, 75, 100};
printf("%lu", sizeof(myNumbers)); // Prints 20
Why did the result show 20 instead of 5, when the array contains 5 elements?
- It is because the sizeof operator returns the size of a type in bytes.
An int data type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements)
= 20 bytes.
Knowing the memory size of an array is great when you are working with larger programs
that require good memory management.
But when you just want to find out how many elements an array has, you can use the
following formula (which divides the size of the array by the size of the first element in the
array):
Example
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

printf("%d", length); // Prints 5

Making Better Loops


In the array loops section, we wrote the size of the array in the loop condition (i < 4). This is
not ideal, since it will only work for arrays of a specified size.
However, by using the sizeof formula from the example above, we can now make loops that
work for arrays of any size, which is more sustainable.
Instead of writing:
Example
int myNumbers[] = {25, 50, 75, 100};
int i;

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


printf("%d\n", myNumbers[i]);
}
It is better to write:
Example
int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

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


printf("%d\n", myNumbers[i]);
}

Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the
average of different ages:
Example
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;


int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Loop through the elements of the array
for (i = 0; i < length; i++) {
sum += ages[i];
}
// Calculate the average by dividing the sum by the length
avg = sum / length;

// Print the average


printf("The average age is: %.2f", avg);
And in this example, we create a program that finds the lowest age among different ages:
Example
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a variable and assign the first array element of ages to it
int lowestAge = ages[0];

// Loop through the elements of the ages array to find the lowest age
for (i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
MULTIDIMENSIONAL ARRAYS
if you want to store data as a tabular form, like a table with rows and columns, you need to
get familiar with multidimensional arrays.
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. The most common; two-dimensional arrays
(2D).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers, take a look at the following example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows [2], while the second dimension represents
the number of columns [3]. The values are placed in row-order, and can be visualized like
this:

Access the Elements of a 2D Array


To access an element of a two-dimensional array, you must specify the index number of both
the row and column.
This statement accesses the value of the element in the first row (0) and third column (2) of
the matrix array.
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2


Remember that: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Change Elements in a 2D Array
To change the value of an element, refer to the index number of the element in each of the
dimensions:
The following example will change the value of the element in the first row (0) and first
column (0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1


Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop for each of the array's
dimensions.
The following example outputs all elements in the matrix array:
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
C POINTERS
Creating Pointers
You learned from the earlier, that we can get the memory address of a variable with the
reference operator &:
Example
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)

✓ A pointer is a variable that stores the memory address of another variable as its
value.
✓ A pointer variable points to a data type (like int) of the same type, and is created
with the * operator.
✓ The address of the variable you are working with is assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address
of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
Example explained
✓ Create a pointer variable with the name ptr, that points to an int variable (myAge). Note
that the type of the pointer has to match the type of the variable you're working with
(int in our example).
✓ Use the & operator to store the memory address of the myAge variable, and assign it to
the pointer.
✓ Now, ptr holds the value of myAge's memory address.
Dereference
In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
// Dereference: Output the value of myAge with the pointer (43)
printf("%d\n", *ptr);
Note that the * sign can be confusing here, as it does two different things in our code:
✓ When used in declaration (int* ptr), it creates a pointer variable.
✓ When not used in declaration, it acts as a dereference operator.
Good To Know: There are two ways to declare pointer variables in C:
int* myNum;
int *myNum;
Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages,
like Python and Java.
They are important in C, because they allow us to manipulate the data in the computer's
memory. This can reduce the code and improve the performance. If you are familiar with data
structures like lists, trees and graphs, you should know that pointers are especially useful for
implementing those. And sometimes you even have to use pointers, for example when
working with files and memory management.
But be careful; pointers must be handled with care, since it is possible to damage data stored
in other memory addresses.

You might also like