Dark Mode On/Off

# Pointer and Arrays in C

When an array in C language is declared, compiler allocates sufficient memory to contain all its elements. Its base address is also allocated by the compiler.

Declare an array arr,

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

Suppose the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:

Variable arr will give the base address, which is a constant pointer pointing to arr[0]. Hence arr contains the address of arr[0] i.e 1000.

arr has two purpose -

• It is the name of the array
• It acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default

For better understanding of the declaration and initialization of the pointer - click here. and refer to the program for its implementation.

NOTE:

• You cannot decrement a pointer once incremented. p-- won't work.

## Pointer to Array

Use a pointer to an array, and then use that pointer to access the array elements. For example,

#include<stdio.h>

void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}

1 2 3

Syntax:

*(a+i)  //pointer with an array

is same as:

a[i]

## Pointer to Multidimensional Array

Let's see how to make a pointer point to a multidimensional array. In a[i][j], a will give the base address of this array, even a + 0 + 0 will also give the base address, that is the address of a[0][0] element.

*(*(a + i) + j)

## Pointer and Character strings

Pointer is used to create strings. Pointer variables of char type are treated as string.

char *str = "Hello";

The above code creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello".

• The string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello";
• The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
• str is a pointer to the string and also name of the string. Therefore we do not need to use indirection operator *.

## Array of Pointers

Pointers are very helpful in handling character arrays with rows of varying lengths.

char *name[3] = {