0% found this document useful (0 votes)
8 views27 pages

C Arrays nd pointer[1]

The document provides a comprehensive overview of arrays in C programming, including their declaration, initialization, and access methods. It covers both one-dimensional and multidimensional arrays, illustrating how to input, modify, and output array elements, as well as examples of using arrays in functions. Additionally, it emphasizes the importance of accessing array elements within bounds to avoid undefined behavior.

Uploaded by

Ankit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views27 pages

C Arrays nd pointer[1]

The document provides a comprehensive overview of arrays in C programming, including their declaration, initialization, and access methods. It covers both one-dimensional and multidimensional arrays, illustrating how to input, modify, and output array elements, as well as examples of using arrays in functions. Additionally, it emphasizes the importance of accessing array elements within bounds to avoid undefined behavior.

Uploaded by

Ankit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

C Arrays

Arrays in C

An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it.

int data[100];

How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, mark , of floating-point type. And its size is 5.


Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed
once it is declared.

Access Array Elements


You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0] , the
second element is mark[1] and so on.

Declare an Array
Few keynotes:
• Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
• If the size of an array is n , to access the last element, the n-1 index is used. In
this example, mark[4]

• Suppose the starting address of mark[0] is 2120d. Then, the address of


the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and
so on.
This is because the size of a float is 4 bytes.
How to initialize an array?
It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {19, 10, 8, 17, 9};

Here, we haven't specified the size. However, the compiler knows its size is 5
as we are initializing it with 5 elements.
Initialize an Array
Here,

mark[0] is equal to 19

mark[1] is equal to 10

mark[2] is equal to 8

mark[3] is equal to 17

mark[4] is equal to 9

Change Value of Array elements

int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1


mark[2] = -1;

// make the value of the fifth element to 0


mark[4] = 0;

Input and Output Array Elements


Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element


scanf("%d", &mark[2]);

// take input and store it in the ith element


scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.


// print the first element of the array
printf("%d", mark[0]);

// print the third element of the array


printf("%d", mark[2]);

// print ith element of the array


printf("%d", mark[i-1]);

Example 1: Array Input/output

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Here, we have used a for loop to take 5 inputs from the user and store them
in an array. Then, using another for loop, these elements are displayed on the
screen.
Example 2: Calculate Average

// Program to find the average of n numbers using arrays

#include <stdio.h>
int main() {

int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);

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


printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];
}

average = sum / n;
printf("Average = %d", average);

return 0;
}

Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Here, we have computed the average of n numbers entered by the user.


Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can access the array elements from testArray[0] to testArray[9] .

Now let's say if you try to access testArray[12] . The element is not available.
This may cause unexpected output (undefined behavior). Sometimes you
might get an error and some other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays
In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays. For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as a table with 3 rows and each row has 4 columns.
Two dimensional Array

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, the array y can hold 24 elements.


Initializing a multidimensional array
Here is how you can initialize two-dimensional and three-dimensional arrays:

Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Initialization of a 3d array

You can initialize a three-dimensional array in a similar way like a two-


dimensional array. Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example 1: Two-dimensional array to store and print values

// C program to store temperature of two cities of a week and display it.


#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}

Output

City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26

Example 2: Sum of two matrices

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

Example 3: Three-dimensional array

// C Program to store and print 12 values entered by the user

#include <stdio.h>
int main()
{
int test[2][3][2];

printf("Enter 12 values: \n");

for (int i = 0; i < 2; ++i)


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with proper index.

printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}

Output

Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

Pass arrays to a function in C


In C programming, you can pass an entire array to functions.
Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a
function.
Example 1: Pass Individual Array Elements

#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}

Output

Here, we have passed array parameters to the display() function in the same
way we pass variables to a function.

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);

We can see this in the function definition, where the function parameters are
individual variables:

void display(int age1, int age2) {


// code
}

Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float num[]) {


float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}

return sum;
}

Output

Result = 162.50

To pass an entire array to a function, only the name of the array is passed as
an argument.

result = calculateSum(num);

However, notice the use of [] in the function definition.

float calculateSum(float num[]) {


... ..
}

This informs the compiler that you are passing a one-dimensional array to the
function.

Pass Multidimensional Arrays to a Function


To pass multidimensional arrays to a function, only the name of the array is
passed to the function (similar to one-dimensional arrays).

Example 3: Pass two-dimensional arrays

#include <stdio.h>
void displayNumbers(int num[2][2]);

int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}

// pass multi-dimensional array to a function


displayNumbers(num);

return 0;
}

void displayNumbers(int num[2][2]) {


printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output

Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

Notice the parameter int num[2][2] in the function prototype and function
definition:

// function prototype
void displayNumbers(int num[2][2]);

This signifies that the function takes a two-dimensional array as an argument.


We can also pass arrays with more than 2 dimensions as a function
argument.

When passing two-dimensional arrays, it is not mandatory to specify the


number of rows in the array. However, the number of columns should always
be specified.

For example,

void displayNumbers(int num[][2]) {


// code
}

Note: In C programming, you can pass arrays to functions, however, you


cannot return arrays from functions.
C Pointers
Pointers are powerful features of C and C++ programming. Before we learn
pointers, let's learn about addresses in C programming.

Address in C
If you have a variable var in your program, &var will give you its address in the
memory.
We have used address numerous times while using the scanf() function.

scanf("%d", &var);

Here, the value entered by the user is stored in the address of var variable.
Let's take a working example.

#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);

// Notice the use of & before var


printf("address of var: %p", &var);
return 0;
}

Output

var: 5
address of var: 2686778

Note: You will probably get a different address when you run the above code.

C Pointers
Pointers (pointer variables) are special variables that are used to store
addresses rather than values.

Pointer Syntax

Here is how we can declare pointers.

int* p;

Here, we have declared a pointer p of int type.


You can also declare pointers in these ways.

int *p1;
int * p2;

Let's take another example of declaring pointers.

int* p1, p2;

Here, we have declared a pointer p1 and a normal variable p2 .

Assigning addresses to Pointers

Let's take an example.

int* pc, c;
c = 5;
pc = &c;

Here, 5 is assigned to the c variable. And, the address of c is assigned to


the pc pointer.
Get Value of Thing Pointed by Pointers

To get the value of the thing pointed by the pointers, we use the * operator.
For example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc); // Output: 5

Here, the address of c is assigned to the pc pointer. To get the value stored in
that address, we used *pc .

Note: In the above example, pc is a pointer, not *pc . You cannot and should
not do something like *pc = &c ;

By the way, * is called the dereference operator (when working with pointers).
It operates on a pointer and gives the value stored in that pointer.

Changing Value Pointed by Pointers

Let's take an example.

int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1

We have assigned the address of c to the pc pointer.


Then, we changed the value of c to 1. Since pc and the address of c is the
same, *pc gives us 1.
Let's take another example.

int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is
the same, c will be equal to 1.
Let's take one more example.

int* pc, c, d;
c = 5;
d = -15;

pc = &c; printf("%d", *pc); // Output: 5


pc = &d; printf("%d", *pc); // Ouptut: -15

Initially, the address of c is assigned to the pc pointer using pc = &c; .

Since c is 5, *pc gives us 5.


Then, the address of d is assigned to the pc pointer using pc = &d; . Since d is -
15, *pc gives us -15.
Example: Working of Pointers

Let's take a working example.

#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Explanation of the program


1. int* pc, c;

Here, a pointer pc and a normal variable c , both of type int , is created.


Since pc and c are not initialized at initially, pointer pc points to either no
address or a random address. And, variable c has an address but contains
random garbage value.

2. c = 22;
This assigns 22 to the variable c . That is, 22 is stored in the memory location
of variable c .

3. pc = &c;

This assigns the address of variable c to the pointer pc .

4. c = 11;

This assigns 11 to variable c .

5. *pc = 2;

This change the value at the memory location pointed by the pointer pc to 2.
Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c . Then,

int c, *pc;

// pc is address but c is not


pc = c; // Error

// &c is address but *pc is not


*pc = &c; // Error
// both &c and pc are addresses
pc = &c; // Not an error

// both c and *pc values


*pc = c; // Not an error

Here's an example of pointer syntax beginners often find confusing.

#include <stdio.h>
int main() {
int c = 5;
int *p = &c;

printf("%d", *p); // 5
return 0;
}

Why didn't we get an error when using int *p = &c; ?

It's because

int *p = &c;

is equivalent to

int *p:
p = &c;

In both cases, we are creating a pointer p (not *p ) and assigning &c to it.
To avoid this confusion, we can use the statement like this:

int* p = &c;
Relationship Between Arrays and
Pointers
Relationship Between Arrays and Pointers
An array is a block of sequential data. Let's write a program to print addresses
of array elements.

#include <stdio.h>
int main() {
int x[4];
int i;

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


printf("&x[%d] = %p\n", i, &x[i]);
}

printf("Address of array x: %p", x);

return 0;
}

Output

&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x .


It is because the size of int is 4 bytes (on our compiler).
Notice that, the address of &x[0] and x is the same. It's because the variable
name x points to the first element of the array.
Relation between Arrays and Pointers
From the above example, it is clear that &x[0] is equivalent to x . And, x[0] is
equivalent to *x .

Similarly,

• &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1) .

• &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2) .

• ...

• Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i) .

Example 1: Pointers and Arrays

#include <stdio.h>
int main() {

int i, x[6], sum = 0;

printf("Enter 6 numbers: ");

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


// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);

// Equivalent to sum += x[i]


sum += *(x+i);
}

printf("Sum = %d", sum);

return 0;
}

When you run the program, the output will be:

Enter 6 numbers: 2
3
4
4
12
4
Sum = 29

Here, we have declared an array x of 6 elements. To access elements of the


array, we have used pointers.
In most contexts, array names decay to pointers. In simple words, array
names are converted to pointers. That's the reason why you can use pointers
to access elements of arrays. However, you should remember that pointers
and arrays are not the same.
There are a few cases where array names don't decay to pointers. To learn
more, visit: When does array name doesn't decay into a pointer?
Example 2: Arrays and Pointers

#include <stdio.h>
int main() {

int x[5] = {1, 2, 3, 4, 5};


int* ptr;

// ptr is assigned the address of the third element


ptr = &x[2];

printf("*ptr = %d \n", *ptr); // 3


printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2

return 0;
}

When you run the program, the output will be:

*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2

In this example, &x[2] , the address of the third element, is assigned to


the ptr pointer. Hence, 3 was displayed when we printed *ptr .

And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-

1) gives us the second element.

You might also like