C program to print array elements and address of each element :
In this tutorial, we will learn how to print the address and elements of an integer array. This example will show you how the elements of an array are stored in the memory.
Let’s take a look at the program :
C program :
#include <stdio.h>
int main()
{
//1
int myArray[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i;
//2
for (i = 0; i < 9; i++)
{
//3
printf("Address for %d is %d\n", myArray[i], &myArray[i]);
}
}
Explanation :
The commented numbers in the above program denote the step number below :
- Create one integer array myArray with some integer values. We will print these numbers and memory address where it is stored. Integer i is used in the loop below.
- Run one for loop to read all numbers from the array. Print each number and its address. For printing the address, we are using &myArray[i] for position i.
Output :
Address for 1 is 1489689280
Address for 2 is 1489689284
Address for 3 is 1489689288
Address for 4 is 1489689292
Address for 5 is 1489689296
Address for 6 is 1489689300
Address for 7 is 1489689304
Address for 8 is 1489689308
Address for 9 is 1489689312
The size of an integer is 4 bytes. That’s why you can see the difference of 4 between each address. Also, all numbers in the array are stored in consecutive contiguous memory locations.
You might also like:
- C program to find total number of sub-array with product less than a value
- C program to find total lowercase,uppercase,digits etc in a string
- C program to read user input and store them in two dimensional array
- C programming tutorial to learn atof, atoi and atol functions
- What is auto variable in C and how it works
- Find ‘sin’ ‘cos’ and ‘tan’ values of a ‘degree’ in C
- C programming example to print the source code of the current program