[go: up one dir, main page]

0% found this document useful (0 votes)
2 views16 pages

What Is A Pointer?

The document provides a comprehensive overview of pointers in C programming, including their declaration, initialization, and various types such as null pointers, double pointers, and function pointers. It also covers dynamic memory allocation, pointer arithmetic, and passing pointers to functions, along with examples for each concept. Additionally, it includes lab practice exercises to reinforce the understanding of pointers.

Uploaded by

sherlockisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

What Is A Pointer?

The document provides a comprehensive overview of pointers in C programming, including their declaration, initialization, and various types such as null pointers, double pointers, and function pointers. It also covers dynamic memory allocation, pointer arithmetic, and passing pointers to functions, along with examples for each concept. Additionally, it includes lab practice exercises to reinforce the understanding of pointers.

Uploaded by

sherlockisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lab – 7

What is a Pointer?
A pointer is a variable that stores the address of another variable.
A pointer is always denoted by (*) asterisk symbol
int *p; // p is a pointer
int p; // p is a variable
• A pointer always holds a computer memory address
• When a variable is declared, a memory location is allocated for that variable in the
Random Access Memory(RAM).
• A memory location is called an address
• The ability of using a memory address (through pointers) usually leads to a
more compact and efficient code.

int id = 123;
int phone = 912345678;
float salary = 30000.00;
int *i, *p;
float *s;
i = &id;
p = & phone ;
s = & salary ;

How to Declare a Pointer?

TAHSINA MUTHAKI 1
Syntax to declare:
data_type *pointer_name;
Example:
int *ptr; // pointer to an integer
char *chPtr; // pointer to a character
float *fPtr; // pointer to a float

How to Initialize?
int num = 10;
int *ptr = # // ptr now stores the address of num

Reference and De-reference operator


❖ & - Reference operator
❖ * - De-reference operator
❖ Reference operator (&) gives us the address of a variable
❖ De-Reference operator (*) gives us the value from the address

int v = 2, *p;
p = &v;

printf("Address of v = %u", &v);


printf("\nAddress of p = %u", &p);
printf("\nValue of p = %u", p);
printf("\nValue of v = %d", *p);

Pointer Assignment
TAHSINA MUTHAKI 2
A poiner can point to other pointer
#include <stdio.h>
int main()
{
int x = 2, y = 3;
int *p, *q;
p = &x;
q = &y;
p = q;
printf("\n%d", p); // Output: 6422036
printf("\n%d", *p); // Output: 3
printf("\n%d", *q); // Output: 3
return 0;
}

Pointer to pointer
A poiner can point to other pointer
#include <stdio.h>
int main()
{
int x = 2;
int *p;
int **q;
p = &x;
q = &p;
printf("\n%d", p); // Output: 6422036
printf("\n%d", *p); // Output: 2
printf("\n%d", *q); // Output: 6422036

TAHSINA MUTHAKI 3
printf("\n%d", **q);// Output: 2
return 0;
}

Modifying Value using pointer


#include <stdio.h>

int main()
{
int x = 2, y = 3;
int *p, *q;
p = &x;
q = &y;
*p = 5;
printf("\n%d", p); // Output: 6422036
printf("\n%d", *p); // Output: 5
printf("\n%d", x); // Output: 5
return 0;
}

sizeof() with Pointer


Gives the size of the pointer itself, not the data it points to.
printf("%lu", sizeof(p)); // typically 4 or 8 bytes depending on the system
Types of Pointers in C
1. Basic Pointer in C
A basic pointer is a variable that stores the memory address of another variable. It’s declared by
placing an asterisk * before the pointer name.
#include <stdio.h>
int main() {

TAHSINA MUTHAKI 4
int a = 10;
int *p = &a;
printf("Address of a: %p\n", p);
printf("Value of a: %d\n", *p);
return 0;
}
2. Null Pointer
A null pointer is a pointer that doesn’t point to any valid memory location. It is usually assigned
the value NULL to indicate it's not initialized.
#include <stdio.h>
int main() {
int *ptr = NULL;
if (ptr == NULL) {
printf("Pointer is null and not pointing to any memory.\n");
}
return 0;
}
3. Double Pointer (Pointer to Pointer)
A double pointer is a pointer that stores the address of another pointer. This is useful for multi-
level data structures.
#include <stdio.h>
int main() {
int val = 100;
int *ptr = &val;
int **pptr = &ptr;
printf("Value using double pointer: %d\n", **pptr);
return 0;
}

TAHSINA MUTHAKI 5
4. Void Pointer
A void pointer is a generic pointer that can point to any data type. It is declared using void *.
#include <stdio.h>
int main() {
int x = 25;
void *ptr = &x;
printf("Value using void pointer: %d\n", *(int *)ptr);
return 0;
}
5. Integer Pointer
An integer pointer holds the address of an int variable.
#include <stdio.h>
int main() {
int num = 42;
int *ptr = &num;
printf("Integer value: %d\n", *ptr);
return 0;
}
6. Float Pointer
A float pointer holds the address of a float variable.
#include <stdio.h>
int main() {
float pi = 3.14;
float *ptr = &pi;
printf("Float value: %.2f\n", *ptr);
return 0;
}

TAHSINA MUTHAKI 6
7. Array Pointer
An array pointer points to the entire array.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
printf("First element: %d\n", *ptr);// Output: 1 (same as arr[0])
printf("%d\n", *(ptr + 1)); // Output: 2 (same as arr[1])
printf("%d\n", *(ptr + 2)); // Output: 3 (same as arr[2])
return 0;
}
8. Function Pointer
A function pointer stores the address of a function.
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
// Declare a function pointer that matches
// the signature of add() fuction
int (*fptr)(int, int);
// Assign address of add()
fptr = &add;
// Call the function via ptr
printf("%d", fptr(10, 5));

TAHSINA MUTHAKI 7
}
9. Wild Pointer
A wild pointer is an uninitialized pointer that may point to an unknown or garbage memory
location. Always initialize pointers before use (e.g., int *wptr = NULL;).
#include <stdio.h>

int main() {
int *ptr; // Wild pointer, not initialized

// Attempting to dereference a wild pointer


// printf("%d\n", *ptr); // This line could cause a crash or undefined behavior

int x = 10;
ptr = &x; // Initialize pointer to a valid address
printf("%d\n", *ptr); // Safe to dereference now

return 0;
}
We need to know about dynamic memory allocation:
Dynamic Memory Allocation in C allows you to allocate memory during runtime, as opposed to
compile time.
Key Functions for Dynamic Memory Allocation
1. malloc() — Allocates a block of memory of specified size and returns a pointer to it.
int *ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
2. calloc() — Allocates memory for an array of elements and initializes all bytes to zero.
int *ptr = (int *)calloc(5, sizeof(int)); // Allocates and initializes memory for 5 integers
3. realloc() — Resizes the allocated memory block.
ptr = (int *)realloc(ptr, 10 * sizeof(int)); // Resizes the array to hold 10 integers
4. free() — Frees the allocated memory.

TAHSINA MUTHAKI 8
free(ptr); // Releases the allocated memory

#include <stdio.h>
#include <stdlib.h>

int main() {
int n;

// Static Memory Allocation (Fixed size at compile time)


int staticArray[5]; // Memory for 5 integers is allocated at compile time
printf("=== Static Memory Allocation ===\n");
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &staticArray[i]);
}

printf("Static Array Elements: ");


for (int i = 0; i < 5; i++) {
printf("%d ", staticArray[i]);
}
printf("\n\n");

// Dynamic Memory Allocation (Size determined at runtime)


printf("=== Dynamic Memory Allocation ===\n");
printf("Enter the number of elements: ");
scanf("%d", &n);

// Allocating memory dynamically

TAHSINA MUTHAKI 9
int *dynamicArray = (int *)malloc(n * sizeof(int));

// Check if memory allocation was successful


if (dynamicArray == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

printf("Enter %d elements:\n", n);


for (int i = 0; i < n; i++) {
scanf("%d", &dynamicArray[i]);
}

printf("Dynamic Array Elements: ");


for (int i = 0; i < n; i++) {
printf("%d ", dynamicArray[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(dynamicArray);

return 0;
}

10. Dangling Pointer


A dangling pointer points to memory that has been freed or deleted.
#include <stdio.h>

TAHSINA MUTHAKI 10
#include <stdlib.h>

int* create() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 42;
free(ptr);
return ptr;
}
int main() {
int *dptr = create();
printf("%d\n", *dptr); // Undefined behavior
return 0;
}

Passing a Pointer to a Function


#include <stdio.h>

// Function to modify a value using a pointer


void modifyValue(int *p) {
*p = 50; // Modifies the original value
}

int main() {
int num = 20;
printf("Before: %d\n", num); // Output: 20
modifyValue(&num);
printf("After: %d\n", num); // Output: 50
return 0;

TAHSINA MUTHAKI 11
}

Function calls: Arguments of a function can be passed to functions in one of the two
ways:
• Sending the values of the arguments (Call by Value)
• Sending the address of the arguments (Call by Reference)

Call by value:
• In Call by Value, a copy of the variable's value is passed to the function.
• Any modification inside the function does not affect the original variable.
#include <stdio.h>

// Function to swap two numbers (Call by Value)


void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
printf("Inside function (Call by Value): x = %d, y = %d\n", x, y);
}

int main() {
int a = 5, b = 10;

printf("Before swap: a = %d, b = %d\n", a, b);

// Call by Value (just passing the values, not the addresses)


swap(a, b);

printf("After swap: a = %d, b = %d\n", a, b); // No change in original values

TAHSINA MUTHAKI 12
return 0;
}

Call by Reference:
• In Call by Reference, the address of the variables is passed to the function.
• This allows the function to directly modify the original values.
#include <stdio.h>

// Function to swap two numbers (Call by Reference)


void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
printf("Inside function (Call by Reference): x = %d, y = %d\n", *x, *y);
}

int main() {
int a = 5, b = 10;

printf("Before swap: a = %d, b = %d\n", a, b);

// Call by Reference (passing the addresses of a and b)


swap(&a, &b);

printf("After swap: a = %d, b = %d\n", a, b); // Values are actually swapped

return 0;
}

How to Pass Array to Function in C?

TAHSINA MUTHAKI 13
1. 1D array
#include <stdio.h>

void printArray(int arr[], int size) {


for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int numbers[] = {10, 20, 30, 40, 50};
int length = sizeof(numbers) / sizeof(numbers[0]);

printArray(numbers, length);

return 0;
}
2. 2D array
#include <stdio.h>
void printMatrix(int matrix[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

TAHSINA MUTHAKI 14
int main() {
int mat[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

printMatrix(mat, 2);

return 0;
}
3. 1D String
#include <stdio.h>
// Function to print a string
void printString(char str[]) {
printf("String: %s\n", str);
}
int main() {
char myString[] = "Hello, World!";
printString(myString); // Passing the string to the function
return 0;
}

4. 1D array using Pointer


#include <stdio.h>
// Function to print an array
void printArray(int *arr, int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", arr[i]);

TAHSINA MUTHAKI 15
}
printf("\n");
}
int main() {
int arr[] = {10, 20, 30, 40};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size); // Output: 10 20 30 40
return 0;
}

Lab Practice:
1. Write a C program to multiply two matrices using pointers.
2. Write a C program to find the length of a string using pointers.
3. Write a C program to compare two strings using pointers.
4. Write a C program to copy one array to another using pointers.
5. Write a C program to reverse an array using pointers.
6. Write a C program to search an element in an array using pointers.
7. Write a C program to return Multiple Values from a Function Using Pointers.

TAHSINA MUTHAKI 16

You might also like