C programming

Chapter 7

Arrays

An array is a collection of simillar datatypes.

one variable = capable of storing multiple values

syntax

The syntax of declaring an array looks like this

char hytek[90]; character array
float hytek[90]; float array
int hytek[90]; integer array                                                                                                              

The values can now be assigned to hytek array like this

hytek[0] = 34;

hytek[1] = 78;

Note : It is very important to note that the array index starts with 0

Accessing elements

Elements of an array can be accessed using

scanf("%d",&hytek[0]);  input first value
printf("%d",&hytek[0]); output first value

Initialization of an Array

There are many other ways in which an arraycan be initialized

int hytek[4] = {3,5,6,7}
float hytek[3] = {3.3,4.4,5.6}
Arrays can be initialized while declaration

Arrays in Memory

int arr [3] = {1,2,3} //1 integer = 4 bytes

This will reserve 4*3 = 12 bytes in memory 4 bytes for each integer

Pointer Arithmetic

A pointer can be incremented to point to the next memory location of that type

Consider this example

int i = 44;
int *q = &i;q=87567
q++;    now q=87571 #address 87567
same for char or float but in char address will incremented to 1 or in float also same as integer

Following operation can be performed on a pointers :

  1. Addition of a number to a pointer
  2. subtraction of a number from a pointer
  3. subtraction of one pointer from another
  4. comparison of two pointer variables

Accessing Arrays using pointers

Consider this array /// if ptr points to index 0,ptr++ will point to index 1& so on…

This way we can have an integer pointer pointing to first element of the array like this

int*ptr=&arr[0]; or simply arr
ptr++
*ptr will have 4 as its value

passing arrays to functions

Arrays can be passed to the function like this

print Array (arr,n); //function call

void print Array(int*i,int n); //function prototype

void print Array (int i [ ],int n);

multidimensional Arrays

an array can  be of 2 dimension /3 dimension /n dimensionA

2 dimensional array can be defined as

int arr [3][2] = {{1.3}
{ 7,6}
{9,8}};

we can access the elements of this array as arr[0][0],arr[0][1],and so on…

2d arrays in memory

a 2d array same as 1d array is stored in contiguous memory blocks like this