0% found this document useful (0 votes)
325 views

pointers (1)

Uploaded by

12215139
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
325 views

pointers (1)

Uploaded by

12215139
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Pointers

Pointers: A pointer in C is a variable that stores the memory address of another


variable. Pointers are one of the most powerful features of C, allowing you to work
with memory, manipulate variables directly, pass references to functions, and handle
arrays and dynamic memory more efficiently.

1. Understanding Pointers

A pointer "points" to a specific location in memory. Instead of holding a value like an


integer or a character, it holds the address of a variable where the value is stored.

Example:

int x = 10;

int *p; // Declare a pointer to an integer

p = &x; // Assign the address of 'x' to 'p'

In this example:

 x holds the value 10.

 p is a pointer that holds the address of x.

 &x returns the address of x.

2. Pointer Declaration

A pointer is declared using the * operator before the variable name. The data type of
the pointer must match the type of the variable it points to.

Syntax:

data_type *pointer_name;

Example:

int *p; // Pointer to an integer

char *ch; // Pointer to a character

float *f; // Pointer to a float

Here, p is a pointer to an int, ch is a pointer to a char, and f is a pointer to a float.


3. Pointer Initialization

A pointer can be initialized by assigning it the address of a variable using the


address-of operator &.

Example:

int a = 5;

int *p = &a; // 'p' now holds the address of 'a'

4. Dereferencing a Pointer

Dereferencing a pointer means accessing the value stored at the memory location
the pointer is pointing to. This is done using the * operator (not to be confused with
pointer declaration).

Example:

int a = 5;

int *p = &a; // 'p' holds the address of 'a'

printf("%d", *p); // Dereferencing 'p', prints the value of 'a', which is 5

 *p gives the value at the memory address held by p, which in this case is 5.

5. NULL Pointer

A NULL pointer is a special pointer that does not point to any valid memory location.
It is used to indicate that the pointer is not currently referencing anything.

Example:

int *p = NULL;

Attempting to dereference a NULL pointer will lead to undefined behavior, often


causing a segmentation fault.

6. Pointer Arithmetic

Pointers in C support arithmetic operations like addition and subtraction. However,


pointer arithmetic is done based on the size of the data type the pointer points to.

Example:
int arr[3] = {10, 20, 30};

int *p = arr;

printf("%d\n", *p); // Output: 10

p++;

printf("%d\n", *p); // Output: 20

p++;

printf("%d\n", *p); // Output: 30

 When p++ is executed, it doesn't just increment the pointer by 1; it moves the
pointer to the next integer's memory location (typically 4 bytes later if it's an
int).

7. Pointers and Arrays

An array name in C is a constant pointer to the first element of the array. The
elements of the array can be accessed using pointers.

Example:

int arr[3] = {10, 20, 30};

int *p = arr; // 'p' now points to the first element of 'arr'

printf("%d\n", *p); // Output: 10 (same as arr[0])

printf("%d\n", *(p + 1)); // Output: 20 (same as arr[1])

printf("%d\n", *(p + 2)); // Output: 30 (same as arr[2])

8. Pointer to Pointer (Double Pointer)

A pointer to a pointer is a pointer that holds the address of another pointer. This can
be useful in various cases like dynamically allocating memory for a 2D array or
passing pointers to functions.

Example:

int a = 10;

int *p = &a; // Pointer to an integer


int **pp = &p; // Pointer to pointer to an integer

printf("%d", **pp); // Output: 10 (Dereferencing twice to get the value of 'a')

9. Pointers and Functions

Pointers can be passed to functions to modify variables in the calling function, or to


pass large structures or arrays efficiently.

Example: Passing Pointers to Functions

#include <stdio.h>

void changeValue(int *p) {

*p = 20; // Change the value at the memory location pointed by 'p'

int main() {

int a = 10;

changeValue(&a); // Pass the address of 'a' to the function

printf("%d", a); // Output: 20 (Value of 'a' is changed inside the function)

return 0;

10. Pointer to Function

A pointer to a function is a pointer that points to the address of a function. Function


pointers can be useful in callback functions and implementing function tables.

Example:

#include <stdio.h>

int add(int a, int b) {

return a + b;

int main() {

int (*func_ptr)(int, int); // Declare a function pointer


func_ptr = add; // Assign address of 'add' function to pointer

printf("%d", func_ptr(3, 4)); // Output: 7 (Calling the function via pointer)

return 0;

11. Dynamic Memory Allocation with Pointers

In C, dynamic memory allocation is done using the malloc(), calloc(), realloc(), and
free() functions. These functions are used to allocate and deallocate memory at
runtime, and they return a pointer to the allocated memory.

Example: malloc() and free()

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers

for (int i = 0; i < 5; i++) {

ptr[i] = i + 1; // Storing values

for (int i = 0; i < 5; i++) {

printf("%d ", ptr[i]); // Accessing values

free(ptr); // Deallocating memory

return 0;

 malloc() allocates memory dynamically.


 free() deallocates the memory to avoid memory leaks.

12. Common Mistakes with Pointers

1. Dereferencing NULL Pointer: Accessing memory via a NULL pointer will


cause a runtime error.

int *ptr = NULL;

printf("%d", *ptr); // Undefined behavior (Segmentation fault)

2. Dangling Pointer: A pointer that points to a memory location that has been
deallocated or no longer valid.

int *p = (int *)malloc(sizeof(int));

*p = 10;

free(p); // Memory is deallocated

// p is now a dangling pointer

3. Memory Leak: Forgetting to free dynamically allocated memory leads to


memory leaks, consuming system memory unnecessarily.

int *p = (int *)malloc(1000 * sizeof(int));

// If free(p) is not called, this memory will not be released.

13. Summary of Key Pointer Concepts

 Pointer Declaration: int *p; declares a pointer to an int.

 Pointer Initialization: p = &a; assigns the address of variable a to pointer p.

 Dereferencing: *p gives the value stored at the address p is pointing to.

 Pointer Arithmetic: Incrementing a pointer (p++) moves it to the next memory


location for that data type.

 Pointers and Arrays: Array names are pointers to their first element. arr[i] is
equivalent to *(arr + i).

 Pointer to Pointer: A pointer can store the address of another pointer (int
**pp).

 Function Pointers: Pointers can point to functions and be used to call


functions.
 Dynamic Memory: malloc(), calloc(), and realloc() are used for dynamic
memory allocation, and free() is used to deallocate memory.

Basic Pointer Declaration and Usage

Question:

What is the output of the following code?

#include <stdio.h>

int main() {

int a = 10;

int *p = &a;

printf("%d", *p);

return 0;

Answer:

Output: 10

Explanation:

 p is a pointer to a, meaning it holds the address of a. The *p dereferences the


pointer, giving the value stored at that address, which is 10.

2. Pointer Arithmetic

Question:

What will be the output of the following program?

#include <stdio.h>

int main() {

int arr[3] = {10, 20, 30};

int *p = arr;

printf("%d", *(p + 1));

return 0;
}

Answer:

Output: 20

Explanation:

 The pointer p points to the first element of the array arr.

 *(p + 1) accesses the second element of the array, which is 20.

3. Pointer and Array Relationship

Question:

What is the output of the following code?

#include <stdio.h>

int main() {

int arr[5] = {1, 2, 3, 4, 5};

int *ptr = arr;

printf("%d", *(ptr + 3));

return 0;

Answer:

Output: 4

Explanation:

 ptr points to the first element of the array.

 *(ptr + 3) gives the value at the 4th position (index 3), which is 4.

4. Null Pointer

Question:

What is a null pointer in C?

Answer:
A null pointer is a pointer that does not point to any valid memory location. In C, it is
typically represented as NULL. A pointer initialized to NULL means it is not assigned
any valid address.

Example:

int *ptr = NULL;

5. Pointer to Pointer (Double Pointer)

Question:

What will be the output of the following code?

#include <stdio.h>

int main() {

int a = 5;

int *p = &a;

int **q = &p;

printf("%d", **q);

return 0;

Answer:

Output: 5

Explanation:

 p is a pointer to a, and q is a pointer to p.

 **q dereferences q twice, first to access p and then to access the value a
holds, which is 5.

6. Pointer Increment and Decrement

Question:

What is the output of the following program?

#include <stdio.h>
int main() {

int x = 5;

int *p = &x;

printf("%d ", *p);

p++;

printf("%d", *p);

return 0;

Answer:

The first print statement will output 5, but the second one results in undefined
behavior because after p++, it points to a memory location beyond x. Accessing this
location is unpredictable.

7. Pointer and Function

Question:

What is the output of the following code?

#include <stdio.h>

void changeValue(int *p) {

*p = 10;

int main() {

int x = 5;

changeValue(&x);

printf("%d", x);

return 0;

Answer:
Output: 10

Explanation:

 changeValue takes a pointer to x and modifies the value at that address.

 The value of x changes from 5 to 10 in the main function.

8. Pointer Size

Question:

What will the following program print on a 64-bit machine?

#include <stdio.h>

int main() {

int *p;

printf("%lu", sizeof(p));

return 0;

Answer:

Output: 8

Explanation:

 On a 64-bit machine, the size of any pointer is 8 bytes because the addresses
are 64-bit long.

9. Pointer to a Function

Question:

Which of the following declares a pointer to a function that returns an int and takes
an int as an argument?

Answer:

The correct declaration is:

int (*ptr)(int);

Explanation:
 This declares ptr as a pointer to a function that takes an int as a parameter
and returns an int.

10. Dynamic Memory Allocation with Pointers

Question:

What is the correct way to dynamically allocate memory for an array of 5 integers in
C?

Answer:

The correct way is:

int *arr = (int *)malloc(5 * sizeof(int));

Explanation:

 malloc allocates memory for 5 integers (5 * sizeof(int)), and the cast (int *)
converts the void pointer returned by malloc to an integer pointer.

11. Dangling Pointer

Question:

What is a dangling pointer in C?

Answer:

A dangling pointer is a pointer that points to a memory location that has been freed
or deallocated. Accessing memory through a dangling pointer can lead to undefined
behavior.

Example:

int *p = (int *)malloc(sizeof(int));

*p = 100;

free(p); // Memory deallocated, but p is still pointing to that memory

12. Pointer and String

Question:

What will be the output of the following program?


#include <stdio.h>

int main() {

char str[] = "Hello";

char *p = str;

printf("%c", *(p + 1));

return 0;

Answer:

Output: e

Explanation:

 The pointer p points to the first character of the string.

 *(p + 1) refers to the second character in the string, which is 'e'.

You might also like