Pointers in C

Pointer Variable in C

A pointer variable is a variable that stores the memory address of another variable.
They are called pointers because they point to a specific location in memory.


Memory Allocation of Variables

When a variable is declared:

  • It is stored in a specific memory location.

  • The compiler and operating system automatically decide where it is placed at runtime.

  • The programmer does not control the exact memory location.


Example Declaration

int x = 3;

This tells the C compiler to:

  1. Reserve space in memory to store an integer value
    (location/address decided by compiler/OS)

  2. Associate the name x with that memory location

  3. Store the value 3 in that location


Accessing Variable Information

1. Size of Allocated Space

printf("%d", sizeof(x));

2. Value Stored in Variable

printf("%d", x);

3. Memory Address of Variable

Use the address-of operator &

printf("%p", &x);
  • &x gives the address of variable x


Declaring a Pointer Variable

Pointers are declared using the indirection operator *

Example

int *p;
  • Creates a pointer variable p

  • It can store the address of an integer variable


Assigning Address to Pointer

p = &x;
  • Now p contains the address of x

  • We say p points to x


Understanding a Pointer

A pointer has two parts:

  1. The pointer itself → holds the address

  2. The address → points to the stored value


Printing Pointer Information

1. Print Address Stored in Pointer

printf("%p", p);

2. Print Value Pointed by Pointer

printf("%d", *p);
  • *p means value stored at the address contained in p



Uses of Pointers in C

Pointers can be used to:

  • Build faster and more efficient code

  • Provide an alternate and efficient way to access data stored in variables and arrays

  • Pass arrays and strings conveniently from one function to another

  • Return more than one value from a function

  • Perform dynamic memory allocation

  • Build complex data structures such as linked lists, trees, etc.


Important Pointer Operators in C

1. Address-of Operator (&)

  • Used to get the memory address of a variable

  • Returns the location where the variable is stored in memory

Example:

&variable

Returns the address of variable


2. Dereference Operator (*)

  • Used to access the value stored at a pointer’s address

  • Also used to declare pointer variables

Example:

*pointer

Accesses the value stored at the memory location pointed to by pointer


Types of Pointers in C

1. NULL Pointer

  • A pointer that does not point to any valid memory location

  • Created by assigning NULL to the pointer

  • Any pointer type can be assigned NULL

Syntax:

data_type *pointer_name = NULL;

2. Void Pointer (Generic Pointer)

  • Pointer of type void

  • Has no associated data type

  • Can store address of any type of variable

Syntax:

void *pointer_name;

3. Constant Pointer

  • The address stored in the pointer is constant

  • Cannot be modified after initialization

  • Always points to the same memory location

Syntax:

data_type * const pointer_name;

4. Pointer to Constant

  • Pointer that points to a constant value

  • The value cannot be modified through the pointer

Syntax:

const data_type *pointer_name;

5. Dangling Pointer

  • A pointer that points to a memory location that has been freed or deleted

  • Occurs when memory is released but the pointer still stores the old address


The following program will illustrate the pointer indirection operator and dereferencing
#include <stdio.h>
int main()
{
int num=5;
int *ptr=&num;
printf(“the value and address of num is %d %p\n”,num,&num);
printf(“the value and address of num using pointer ptr is %d %p\n”,*ptr,ptr);
*ptr=15;                     // indirection, which stores value in variable num using the pointer ptr.
printf(“the value of num after indirect initialization is %d\n”,num);

the value and address of num is 5 0x7ffe6246e2fc
the value and address of num using pointer ptr is 5 0x7ffe6246e2fc
the value of num after indirect initialization is 15

The following program uses a call by reference mechanism to modify a variable value using pointers
#include <stdio.h>
void f(int *x) // x is a pointer to n
{
*x=*x+1; //accessing the actual content
}
int main()
{
int n=10;

f(&n); //calling the function with address/reference
printf("n in main =%d\n",n);
//note..... value of n changed in main
}

The following program use pointers to add two numbers using a  function add
int add(int *p1,int *p2)
          return(*p1+*p2);
 }


Write a function calculates the roots of a quadratic equation with coefficients a, b, and c (passed as pointer parameters).

#include <stdio.h>
int main()
{
    int a=10,b=12,sum;
    sum=add(&a,&b);
    printf("Sum=%d",sum);
}
#include <stdio.h>
#include <math.h>

void findRoots(float *a, float *b, float *c) {
    float discriminant, root1, root2, realPart, imagPart;

    discriminant = (*b) * (*b) - 4 * (*a) * (*c);

    if (*a == 0) {
        printf("Not a quadratic equation.\n");
        return;
    }

    printf("\nQuadratic equation: %.2fx^2 + %.2fx + %.2f = 0\n", *a, *b, *c);

    if (discriminant > 0) {
        root1 = (-(*b) + sqrt(discriminant)) / (2 * (*a));
        root2 = (-(*b) - sqrt(discriminant)) / (2 * (*a));
        printf("Real and distinct roots: %.2f and %.2f\n", root1, root2);
    }
    else if (discriminant == 0) {
        root1 = root2 = -(*b) / (2 * (*a));
        printf("Real and equal roots: %.2f and %.2f\n", root1, root2);
    }
    else {
        realPart = -(*b) / (2 * (*a));
        imagPart = sqrt(-discriminant) / (2 * (*a));
        printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n",
               realPart, imagPart, realPart, imagPart);
    }
}


Write a C program to read an array of 5 integers.Use a pointer to find and print the largest element of the array.(university question)
#include <stdio.h>

int main() {
    int arr[5];
    int *ptr;
    int i, max;

    printf("Enter 5 integers:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    ptr = arr;          // Pointer points to the beginning of the array
    max = *ptr;         // Assume the first element is the largest

    for (i = 1; i < 5; i++) {
        if (*(ptr + i) > max) {
            max = *(ptr + i);
        }
    }

    printf("The largest element in the array is: %d\n", max);

    return 0;
}


Write a C program to concatenate two strings using pointers ( university question)

#include <stdio.h>

void concatenate(char *str1, char *str2) {
    // Move the pointer to the end of the first string
    while (*str1 != '\0') {
        str1++;
    }

    // Copy characters from str2 to the end of str1
    while (*str2 != '\0') {
        *str1 = *str2;
        str1++;
        str2++;
    }

    *str1 = '\0'; // Null-terminate the result
}

int main() {
    char str1[200], str2[100];

    printf("Enter the first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter the second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove newline characters if present
    for (int i = 0; str1[i] != '\0'; i++) {
        if (str1[i] == '\n') {
            str1[i] = '\0';
            break;
        }
    }
    for (int i = 0; str2[i] != '\0'; i++) {
        if (str2[i] == '\n') {
            str2[i] = '\0';
            break;
        }
    }

    // Concatenate using pointers
    concatenate(str1, str2);

    printf("Concatenated string: %s\n", str1);

    return 0;
}

Output
Enter the first string: abbc def
Enter the second string: hij kls
Concatenated string: abbc defhij kls

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