Arrays and Pointers
Arrays and Pointers
#include <stdio.h>
int main()
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{
scanf("%d", x+i); // Equivalent to scanf("%d", &x[i]);
sum += *(x+i); // Equivalent to sum += x[i]
}
printf("Sum = %d", sum);
return 0;
}
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29
Pointer to an array
• Pointer to an array is also known as array
pointer.
• Syntax: data type (*var name)[size of array];
// pointer to an array of five numbers
int (* ptr)[5] = NULL;
(or)
int a[3] = {3, 4, 5 };
int *ptr = a;
#include <stdio.h>
int main()
{
int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };
int i = 0;
a = &b;
for (i = 0; i < 5; i++)
printf("%d\n", *(*a + i));
return 0;
}
Output:
1
2
3
4
5
Array of pointers
• “Array of pointers” is an array of the pointer
variables.
• It is also known as pointer arrays.
Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
#include <stdio.h>
int SIZE = 3;
void main()
{
int arr[] = { 1, 2, 3 };
int i, *ptr[SIZE];
for (i = 0; i < SIZE; i++)
{
ptr[i] = &arr[i];
}
for (i = 0; i < SIZE; i++)
{
printf("Value of arr[%d] = %d\n", i, *ptr[i]);
}
}
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3
An array of pointers to the character
to store a list of strings
#include <stdio.h>
int size = 4;
void main()
{
char* names[] = {"amit“, "amar", "ankit", "akhil”};
int i = 0;
for (i = 0; i < size; i++)
{
printf("%s\n", names[i]);
}
}
Output:
amit
amar
ankit
akhil
Pointer to Pointer (Double Pointer)
• The first pointer is used to store the address of
the variable. And the second pointer is used to
store the address of the first pointer. That is
why they are also known as double-pointers.
• We can use a pointer to a pointer to change the
values of normal pointers or create a variable-
sized 2-D array.
• A double pointer occupies the same amount of
space in the memory stack as a normal pointer.
Declaration of Pointer to a Pointer
data_type_of_pointer **name_of_variable =
&normal_pointer_variable;