Skip to main content

Array and Pointers in C


Pointers and arrays are inseparably related, but they are not synonymous.
An array is a non empty set of sequentially indexed element having the same type of data. Each element of the array has a unique identifying index number. Changes made to one element do not affect the other elements. An array occupies contiguous block of memory.
Array notation(int a[10]) is a form of pointer notation. The name of an array is the beginning address of the array, called the base address of the array. It is the address of the zeroth element of the array. The array name is the address constant.So *a will get the zeroth element and *(a+1) will get you the first element and so on.The indirection operator * implies that value at address a[i] is equivalent to *(a+i).

Execute this program to know the concept
#include <stdio.h>
int main()
{
int a[]={10,20,30,40,50};
printf(“%d %u %u %d %u %u %d”,a[0],a,&a[0], *a,&a[1],(a+1),*(a+1));
}
Note that a[0] and *a will print the zeroth element that is 10.
a and &a[0] will print the base address( starting address of the array).
&a[1] and (a+1) will print the address of first element.
*(a+1) will print the first element ie;20.

It is possible to assign an array to a pointer.
int a[10];
int *p;
p=a or p=&a[0]

The pointer to an array does not always point to the first element of the array. It can point to any element of the array.
p=a+3 will point to the third element of the array.

The array elements can be accessed using pointers in the usual way

p[0],p[1] or *p, *(p+1) 
 
Each value of ‘a’ is accessed by using p++ to move from one element to another. When a pointer is incremented, its value is increased by the size of the datatype that it points to. This length is called the “scale factor”.For example if the base address of the array 'a' is 1000.

The relationship between pointer p and variable a is shown below −
P = &a[0] = 1000 

P+1 = &a[1] = 1004 

P+2 = &a[2] = 1008

P+3 = &a[3] = 1012 

P+4 = &a[4] = 1016

Address of an element is calculated using its index and the scale factor of the datatype. 

Example
Address of a[3]=base address+(3*scale factor of int)
=1000+(3*4)
=1000+12
=1012*(p+3) gives the value of a[3] 

a[i] = *(p+i)

It seems that array name and pointer, which points to the base address of the array are equivalent. But it is not true.
When the memory is allocated for array, the starting address is fixed ie; it cannot be changed during the program execution. Therefore the array name is the address constant, the value contained in it should not be changed.That is array cannot be used as lvalue(left value) but a pointer can be.

Predict the output of the following C program code. ( university question)
void main () {
int a[] = {30, 20, 10};
printf(“%d %d %d\n”, *a, *a+1, *(a+1));
}
output:
30 31 20

 Difference between Arrays and Pointers

Arrays
Pointers
Arrays allocate space automatically
It cannot be resized
It cannot be re assigned
sizeof(arrayname) gives the number of bytes occupied by the array
It is explicitly assigned to point to an allocated space.
It can be resized using realloc().
It can be re assigned.
sizeof(p) returns the number of bytes used to store the pointer variable p.
 
 
The following program will read 5 numbers and print even numbers from it using pointer to array.
#include <stdio.h>
void main()
{
 int a[5],i;
 int *p;
 p=a;
 printf("\nenter 5 numbers...\n");
 for(i=0;i<5;i++)
 scanf("%d",(p+i));
 printf("\neven numbers..\n");
 for (i=0;i<5;i++)
 if (*(p+i)%2==0) printf("%d\n",*(p+i));
 }
Compute sum of the elements stored in an array using pointers and user defined function.
#include <stdio.h>
int sumarray(int *ptr,int n)
  {
      int i,sum=0;
      for(i=0;i<10;i++,ptr++)
      {
         sum=sum+*ptr; 
      }
      return sum;
  }
int main()
{
     int a[10]={2,3,4,5,6,7,1,9,10,8};
     int sum;
     sum=sumarray(a,10);
     printf("Sum of array elements=%d\n",sum);
}

O/P
Sum of array elements=55

Write a C program using pointers to compute the Sum and Mean of all elements stored in an array of n real numbers.
#include <stdio.h>

// Function to compute sum and mean using pointers
void sumandmean(float *arr, int n, float *sum, float *mean) {
    *sum = 0.0; // Initialize sum to 0

    // Compute sum of array elements
    for (int i = 0; i < n; i++) {
        *sum += *(arr + i); // Add each element to sum
    }

    // Compute mean
    *mean = *sum / n;
}

int main() {
    float arr[100]; // Array to store real numbers
    int n; // Number of elements in the array
    float sum, mean; // Variables to store sum and mean

    // Input the number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d real numbers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%f", &arr[i]);
    }

    // Compute sum and mean using pointers
    sumandmean(arr, n, &sum, &mean);

    // Display sum and mean
    printf("Sum of all elements: %.2f\n", sum);
    printf("Mean of all elements: %.2f\n", mean);

    return 0;
}

Write a function in C which takes the address of a single dimensional array (containing a finite sequence of numbers) and the number of numbers stored in the array as arguments and stores the numbers in the same array in reverse order. Use pointers to access the elements of the array.( university question)
#include <stdio.h>
void reverse(int *ptr,int n)
{
int i,j,temp;
for(i=0,j=n-1;i<j;i++,j--)
{
temp=*(ptr+i);
*(ptr+i)=*(ptr+j);
*(ptr+j)=temp;
}

}
int main()
{
int a[10]={3,2,4,1,5,7,8,9,6,0};
int i;
reverse(a,10);
printf("The reversed array is\n");
for(i=0;i<10;i++)
printf("%2d",a[i]);
}
Read an array using pointers and print only even numbers.(use dynamic memory allocation)
#include <stdio.h>
#include <stdlib.h>
int main()
{  
  int *p,i,n;
  printf("Enter.....n\n");
  scanf("%d",&n);
  p=(int *)malloc(n*sizeof(int));
  printf("Enter array elements...\n");
  for(i=0;i<n;i++)
  scanf("%d",p+i);
  printf("Even numbers in the array...\n");
  for(i=0;i<n;i++)
  if(*(p+i)%2==0) printf("%d\n",*(p+i));
}
Reverse a string using pointers.( university qn)
#include <stdio.h>
#include <string.h>
  
// Function to reverse the string
// using pointers
void mystrrev(char *pstr)
{
    int i,j;
    char t;
    for(i=0;*(pstr+i)!='\0';i++); // finding the end of the string
    i--;
    
    for(j=0;j<i;i--,j++)   // swapping characters first and last
    {t=*(pstr+i);
    *(pstr+i)=*(pstr+j);
    *(pstr+j)=t;
    }
    

int main()
{
  
    // Get the string
    char str[100];
    printf("Enter a string:);
    scanf("%[^\n]",str);
  
    // Reverse the string
    mystrrev(str);
  
    // Print the result
    printf("Reverse of the string: %s\n", str);
      return 0;
}
Write a C program to print the elements of an array in reverse order using pointers.( uq)
#include <stdio.h>
int main()
{
    int a[100];
    int n,i,*p;
    p=a;
    printf("Enter n\n");
    scanf("%d",&n);
    printf("Enter the array elements\n");
    for(i=0;i<n;i++) {scanf("%d",p);p++;}
    p--;
    printf("Array elements in reverse order\n");
    for(i=0;i<n;i++)
     {printf("%d ",*p);p--;}
    return 0;
}

Programs to try
Do the following using pointers
1.
i) add two numbers
ii) swap two numbers using a user defined function
2. Input and Print the elements of an array using pointers
3. Compute sum of the elements stored in an array using pointers and user defined function.
4.Read an array using pointers and print only even numbers.(use dynamic memory allocation)
5.Compute sum of the elements stored in an array using pointers and user defined function.
6.Write a function in C which takes the address of a single dimensional array (containing a finite sequence of numbers) and the number of numbers stored in the array as arguments and stores the numbers in the same array in reverse order. Use pointers to access the elements of the array.
7.Write a recursive function using char pointer to print the string in reverse order.
8.Write a recursive function using char pointer to find the length of the string.
9.Reverse a string using pointers.( university qn)
10.Write a C program to print the elements of an array in reverse order using pointers.


Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar

Arrays in C-single and multi dimensional arrays- list and matrix

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list(vector); A two dimensional array is like a table(matrix). We can have more dimensions. Always, Contiguous (adjacent) memory locations are used to store array elements in memory. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Declaring  Single Dimensional Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for mentioning dimension of the array.  Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.  In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allo