Array and Pointers in C

  

Pointers and Arrays in C

Pointers and arrays are closely related, but they are not synonymous.


Arrays

  • An array is a non-empty set of sequentially indexed elements having the same data type.

  • Each element has a unique index number, and changes to one element do not affect others.

  • An array occupies a contiguous block of memory.

  • The array name represents the base address (address of the zeroth element).

Array notation and pointers:

int a[10];
  • *a gives the zeroth element.

  • *(a+1) gives the first element.

  • a[i] is equivalent to *(a + i).


Example Program

#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)); return 0; }

Explanation:

  • a[0] and *a → prints 10 (zeroth element)

  • a and &a[0] → prints base address of the array

  • &a[1] and (a+1) → prints address of first element

  • *(a+1) → prints 20 (first element)


Pointers to Arrays

  • You can assign an array to a pointer:

int a[10]; int *p; p = a; // or p = &a[0]
  • A pointer does not have to point to the first element; it can point to any element:

p = a + 3; // points to the 3rd element
  • Array elements can be accessed using the pointer:

p[0], p[1] // or *p, *(p+1)
  • Incrementing a pointer moves it by the size of its data type (scale factor).

Memory example (int = 4 bytes):

PointerAddress
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 calculation:

Address of a[3] = base address + (3 * sizeof(int)) = 1000 + (3 * 4) = 1012
  • Accessing element:

a[i] = *(p + i)

Important Note

  • The array name is a constant address and cannot be changed.

  • Pointers are modifiable, so they can point to different memory locations.

  • Array cannot be used as an lvalue, but a pointer can.


Example Question

void main() { int a[] = {30, 20, 10}; printf("%d %d %d\n", *a, *a+1, *(a+1)); }

Output:

30 31 20

Explanation:

  • *a → 30

  • *a + 1 → 30 + 1 = 31

  • *(a+1) → 20


Difference between Arrays and Pointers

ArraysPointers
Space is allocated automatically    Must be explicitly assigned to allocated space
Cannot be resized    Can be resized using realloc()
Cannot be reassigned    Can be reassigned to different addresses
sizeof(arrayname) → total bytes of array  sizeof(p) → bytes used by pointer variable

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

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays