Array, Pointer and String

By Notes Vandar

Array, Pointer and String

5.1 Concept of array

Concept of Array in C

An array in C is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to group related variables under a single name and access them using an index.

Key Concepts of Arrays

  1. Declaration and Initialization:
    • Declaration: Specifies the array’s type and size.
    • Initialization: Assigns values to the array elements.
  2. Indexing:
    • Zero-based Indexing: Array indices start from 0. The first element is accessed with index 0, the second with index 1, and so on.
  3. Accessing Elements:
    • Elements are accessed using the array name followed by an index in square brackets.
  4. Multidimensional Arrays:
    • Arrays can have more than one dimension, allowing the creation of matrices or tables.
  5. Memory Allocation:
    • Arrays are allocated contiguously in memory. This means that elements are stored next to each other.

Array Declaration and Initialization

  1. Single-Dimensional Array:
    • Declaration:
      int arr[5]; // Declares an array of 5 integers
    • Initialization:
      int arr[5] = {1, 2, 3, 4, 5}; // Initializes the array with values
  2. Multi-Dimensional Array:
    • Declaration:
      int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns
    • Initialization:
      int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

Examples

  1. Single-Dimensional Array Example:

    #include <stdio.h>

    int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    for (int i = 0; i < 5; i++) {
    printf(“Element at index %d: %d\n”, i, arr[i]);
    }
    return 0;
    }

    Explanation:

    • The arr array stores 5 integers.
    • A for loop is used to access and print each element.
  2. Multi-Dimensional Array Example:

    #include <stdio.h>

    int main() {
    int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
    for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
    printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
    }
    }
    return 0;
    }

    Explanation:

    • The matrix array represents a 2D array (2 rows and 3 columns).
    • Nested for loops are used to access and print each element.

Array Operations

  1. Traversal: Accessing each element of the array in sequence.
  2. Insertion: Adding elements at specific positions (for dynamic arrays).
  3. Deletion: Removing elements and shifting others (for dynamic arrays).
  4. Searching: Finding an element in the array.
  5. Sorting: Arranging elements in a specific order (e.g., ascending or descending).

Limitations of Arrays

  1. Fixed Size: The size of an array must be known at compile time and cannot be changed during runtime.
  2. Memory Usage: Large arrays can consume a lot of memory.
  3. No Built-In Bounds Checking: Accessing elements out of the array’s bounds can lead to undefined behavior.

 

5.2 Array declare, access and initialization.

Array Declaration, Access, and Initialization in C

Arrays are fundamental in C for managing collections of related data. Understanding how to declare, access, and initialize arrays is essential for effective programming.

1. Array Declaration

Declaration specifies the type of elements and the size of the array.

Syntax:

type arrayName[size];
  • type: The data type of the array elements (e.g., int, float, char).
  • arrayName: The name of the array.
  • size: The number of elements the array can hold.

Examples:

  1. Integer Array:
    int numbers[5]; // Declares an array of 5 integers
  2. Character Array:
    char letters[10]; // Declares an array of 10 characters

    3.Float Array:
    float prices[3]; // Declares an array of 3 floats

2. Array Initialization

Initialization assigns values to array elements at the time of declaration.

Syntax:

type arrayName[size] = {value1, value2, …, valueN};
  • If fewer values are provided than the size, the remaining elements are initialized to zero (for numeric types) or null (\0) for characters.

Examples:

  1. Integer Array Initialization:
    int numbers[5] = {1, 2, 3, 4, 5}; // Initializes with 5 values

    If you omit the size:

    int numbers[] = {1, 2, 3, 4, 5}; // Size is determined automatically

    2.Character Array Initialization
    :
    char letters[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};

    For strings:

    char greeting[] = “Hello”; // Initializes with “Hello” and adds null terminator
  2. Float Array Initialization:
    float prices[3] = {10.5, 20.0, 30.75};

3. Array Access

Accessing Elements:

  • Elements of an array are accessed using the index (starting from 0).

Syntax:

arrayName[index]

Examples:

  1. Accessing an Element:
    int numbers[5] = {1, 2, 3, 4, 5};
    int value = numbers[2]; // Accesses the element at index 2 (value is 3)
  2. Modifying an Element:
    numbers[1] = 10; // Changes the element at index 1 to 10
  3. Using Loops:
    int i;
    for (i = 0; i < 5; i++) {
    printf(“Element at index %d: %d\n”, i, numbers[i]);
    }

4. Multi-Dimensional Arrays

Declaration and Initialization:

  1. Two-Dimensional Array:
    int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns

    Initialization:

    int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
  2. Accessing Elements:
    int value = matrix[1][2]; // Accesses the element at row 1, column 2 (value is 6)

    Using Nested Loops:

    int i, j;
    for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++) {
    printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
    }
    }

5.3 multi-dimensional array

A multi-dimensional array is an array of arrays. It extends the concept of a one-dimensional array to multiple dimensions, such as 2D matrices or 3D tables. Multi-dimensional arrays are useful for representing complex data structures like grids, tables, or matrices.

1. Declaration

To declare a multi-dimensional array, you specify the number of elements in each dimension.

Syntax:

type arrayName[size1][size2]…[sizeN];
  • type: Data type of the array elements.
  • arrayName: The name of the array.
  • size1, size2, …, sizeN: The sizes of each dimension.

Examples:

  1. Two-Dimensional Array:
    int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns
  2. Three-Dimensional Array:
    int tensor[2][3][4]; // Declares a 3D array with 2 layers, 3 rows, and 4 columns

2. Initialization

Syntax:

type arrayName[size1][size2]…[sizeN] = { { {value1, value2, …}, {…} }, {…} };
  • Values for each dimension are enclosed in braces {}.

Examples:

  1. Two-Dimensional Array Initialization:
    int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
  2. Three-Dimensional Array Initialization:
    int tensor[2][2][3] = {
    { {1, 2, 3}, {4, 5, 6} },
    { {7, 8, 9}, {10, 11, 12} }
    };

3. Accessing Elements

Elements in multi-dimensional arrays are accessed using multiple indices.

Syntax:

arrayName[index1][index2]…[indexN]

Examples:

  1. Accessing 2D Array Elements:
    int value = matrix[1][2]; // Accesses the element at row 1, column 2 (value is 6)
  2. Accessing 3D Array Elements:
    int value = tensor[1][0][2]; // Accesses the element at layer 1, row 0, column 2 (value is 9)

4. Using Loops with Multi-Dimensional Arrays

Two-Dimensional Arrays:

#include <stdio.h>

int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
}
}

return 0;
}

Three-Dimensional Arrays:

#include <stdio.h>

int main() {
int tensor[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};

for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
printf(“Element at [%d][%d][%d]: %d\n”, i, j, k, tensor[i][j][k]);
}
}
}

return 0;
}

5.4 Concept of Pointer

A pointer is a variable that stores the memory address of another variable. Pointers are a powerful feature in C, enabling direct memory manipulation and dynamic memory management. Understanding pointers is crucial for advanced C programming tasks, including data structures, dynamic allocation, and system-level programming.

1. Basic Concept

  • Definition: A pointer holds the address of a variable rather than the variable’s value.
  • Syntax:
    type *pointerName;

Examples:

int *ptr; // Declares a pointer to an integer

2. Pointer Declaration and Initialization

  • Declaration: Specifies the type of data the pointer will point to.
  • Initialization: Assigns the address of a variable to the pointer.

Examples:

int x = 10; // An integer variable
int *ptr = &x; // Pointer ptr now holds the address of x

Explanation:

  • int *ptr: Declares ptr as a pointer to an int.
  • &x: The address-of operator (&) gives the memory address of x.

3. Dereferencing Pointers

  • Dereferencing: Accessing the value stored at the address pointed to by the pointer.
  • Syntax:
    *pointerName

Examples:

int x = 10;
int *ptr = &x;
printf(“Value of x: %d\n”, *ptr); // Dereferencing ptr to get the value of x

Explanation:

  • *ptr: Accesses the value at the address stored in ptr.

4. Pointer Arithmetic

Pointers can be incremented or decremented to navigate through memory addresses.

  • Increment: Moves to the next memory location of the pointer type.
  • Decrement: Moves to the previous memory location.

Examples:

int arr[3] = {1, 2, 3};
int *ptr = arr;

printf(“First element: %d\n”, *ptr); // Outputs 1
ptr++; // Moves to the next integer location
printf(“Second element: %d\n”, *ptr); // Outputs 2

Explanation:

  • ptr++: Advances the pointer to the next integer (4 bytes ahead).

5. Null Pointer

A null pointer is a pointer that points to nothing, represented by NULL or 0.

Examples:

int *ptr = NULL; // Initializes pointer to NULL
if (ptr == NULL) {
printf(“Pointer is null\n”);
}

Explanation:

  • NULL: A constant defined in <stddef.h> representing a null pointer.

6. Pointers and Arrays

  • Pointer Arithmetic: Arrays and pointers are closely related; array names are pointers to the first element.
  • Accessing Array Elements:
    int arr[3] = {1, 2, 3};
    int *ptr = arr; // Equivalent to int *ptr = &arr[0];
    printf(“First element: %d\n”, *ptr); // Outputs 1
    printf(“Second element: %d\n”, *(ptr + 1)); // Outputs 2

7. Function Pointers

Pointers can also point to functions, allowing dynamic function calls.

Syntax:

returnType (*functionPointerName)(parameterTypes);

Examples:

#include <stdio.h>

// Function declaration
void sayHello() {
printf(“Hello, world!\n”);
}

int main() {
void (*funcPtr)() = sayHello; // Pointer to function
funcPtr(); // Calling the function via pointer
return 0;
}

Explanation:

  • void (*funcPtr)(): Declares a pointer to a function returning void and taking no parameters.

8. Dynamic Memory Allocation

Pointers are used for dynamic memory allocation with functions such as malloc(), calloc(), and free().

Examples:

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

int main() {
int *arr = (int *)malloc(3 * sizeof(int)); // Allocates memory for 3 integers
if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

for (int i = 0; i < 3; i++) {
printf(“Element %d: %d\n”, i, arr[i]);
}

free(arr); // Frees allocated memory
return 0;
}

Explanation:

  • malloc(): Allocates a block of memory and returns a pointer to it.
  • free(): Deallocates previously allocated memory.

5.5 Pointer address, dereference, declaration, assignment,
initialization

Pointers in C are variables that store memory addresses of other variables. Understanding how to work with pointers involves concepts such as pointer address, dereferencing, declaration, assignment, and initialization.


1. Pointer Declaration

Declaration of a pointer specifies the type of data the pointer will point to.

Syntax:

type *pointerName;
  • type: The data type of the variable that the pointer will point to.
  • pointerName: The name of the pointer variable.

Examples:

int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float

2. Pointer Initialization

Initialization involves assigning the address of a variable to a pointer.

Syntax:

pointerName = &variableName;
  • &variableName: The address-of operator (&) retrieves the memory address of variableName.

Examples:

int x = 10;
int *ptr = &x; // Initializes ptr with the address of x

Explanation:

  • ptr now points to the address of x.

3. Pointer Address

The address stored in a pointer is the location of a variable in memory.

Syntax:

address = &variable;

Examples:

int x = 10;
int *ptr = &x;
printf(“Address of x: %p\n”, (void *)ptr); // %p format specifier prints the address

Explanation:

  • %p is used to print the address stored in a pointer.

4. Dereferencing Pointers

Dereferencing a pointer accesses the value stored at the address that the pointer points to.

Syntax:

value = *pointerName;
  • *pointerName: The dereference operator (*) accesses the value at the address contained in pointerName.

Examples:

int x = 10;
int *ptr = &x;
printf(“Value at ptr: %d\n”, *ptr); // Dereferences ptr to get the value of x

Explanation:

  • *ptr retrieves the value of x through the pointer ptr.

5. Pointer Assignment

Assignment involves setting a pointer to point to the address of a variable.

Syntax:

pointerName = &variableName;

Examples:

int x = 10;
int y = 20;
int *ptr;

ptr = &x; // ptr now points to x
ptr = &y; // ptr now points to y

Explanation:

  • The pointer ptr can be reassigned to point to different variables.

6. Putting It All Together

Here’s a complete example demonstrating declaration, initialization, address retrieval, dereferencing, and assignment:

Example Code:

#include <stdio.h>

int main() {
int x = 10; // Regular variable
int *ptr; // Pointer declaration

ptr = &x; // Pointer initialization with the address of x

// Display address and value
printf(“Address of x: %p\n”, (void *)ptr); // Pointer address
printf(“Value at ptr: %d\n”, *ptr); // Dereferencing the pointer

int y = 20;
ptr = &y; // Reassign pointer to point to y

// Display new address and value
printf(“Address of y: %p\n”, (void *)ptr); // New pointer address
printf(“Value at ptr: %d\n”, *ptr); // Dereferencing the new pointer

return 0;
}

Explanation:

  • Pointer ptr is first initialized to point to x, then reassigned to point to y.
  • Address and values are printed using the pointer.

 

5.6 Pointer Arithmetic

Pointer arithmetic involves operations on pointers that allow you to navigate through memory locations. This can be useful for traversing arrays or managing dynamic memory. Here’s a detailed look at how pointer arithmetic works in C.


1. Basic Pointer Arithmetic Operations

  1. Increment and Decrement:
    • Increment (++): Moves the pointer to the next memory location of its type.
    • Decrement (--): Moves the pointer to the previous memory location of its type.

Syntax:

pointer++;
pointer–;

Examples:

int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer to the first element of the array

printf(“Value at ptr: %d\n”, *ptr); // Outputs 10
ptr++; // Moves to the next integer location
printf(“Value at ptr: %d\n”, *ptr); // Outputs 20

Explanation:

  • ptr++ advances the pointer by sizeof(int) bytes (usually 4 bytes), so it now points to arr[1].
  1. Addition and Subtraction:
    • Addition (+): Moves the pointer forward by a number of elements.
    • Subtraction (-): Moves the pointer backward by a number of elements.

Syntax:

pointer + n; // Moves pointer forward by n elements
pointer – n; // Moves pointer backward by n elements

Examples:

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

printf(“Value at ptr + 2: %d\n”, *(ptr + 2)); // Outputs 3
printf(“Value at ptr – 1: %d\n”, *(ptr – 1)); // Undefined behavior, ptr – 1 is outside array bounds

Explanation:

  • ptr + 2 advances the pointer by 2 elements (so it points to arr[2]).

2. Pointer Comparison

Pointers can be compared using relational operators.

  • Equal (==): Checks if two pointers point to the same location.
  • Not Equal (!=): Checks if two pointers point to different locations.
  • Less Than (<): Checks if a pointer points to a location before another pointer.
  • Greater Than (>): Checks if a pointer points to a location after another pointer.
  • Less Than or Equal (<=): Checks if a pointer is before or at the same location as another pointer.
  • Greater Than or Equal (>=): Checks if a pointer is after or at the same location as another pointer.

Examples:

int arr[3] = {10, 20, 30};
int *ptr1 = &arr[0];
int *ptr2 = &arr[2];

if (ptr1 < ptr2) {
printf(“ptr1 points to an earlier location than ptr2\n”);
}

Explanation:

  • ptr1 < ptr2 checks if ptr1 points to a lower memory address than ptr2.

3. Pointer Arithmetic with Arrays

Arrays and pointers are closely related; the name of an array is a pointer to its first element. Pointer arithmetic can be used to traverse arrays efficiently.

Example:

#include <stdio.h>

int main() {
int arr[4] = {1, 2, 3, 4};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];

for (int i = 0; i < 4; i++) {
printf(“Element %d: %d\n”, i, *(ptr + i)); // Access array elements using pointer arithmetic
}

return 0;
}

Explanation:

  • *(ptr + i) accesses the i-th element of the array, leveraging pointer arithmetic.

4. Pointer Arithmetic with Structs

Pointers can be used with structs, and pointer arithmetic can navigate through arrays of structs.

Example:

#include <stdio.h>

typedef struct {
int id;
char name[20];
} Student;

int main() {
Student students[3] = {{1, “Alice”}, {2, “Bob”}, {3, “Charlie”}};
Student *ptr = students; // Pointer to the first element of the array of structs

for (int i = 0; i < 3; i++) {
printf(“Student %d: %d, %s\n”, i + 1, (ptr + i)->id, (ptr + i)->name);
}

return 0;
}

Explanation:

  • (ptr + i)->id accesses the id field of the i-th Student in the array.

 

5.7 Array and Pointer

Arrays and pointers are fundamental concepts in C programming that are closely related. Understanding their relationship helps with efficient memory management and manipulation of data structures.


1. Array Overview

An array is a collection of elements of the same type stored in contiguous memory locations. The array name represents a pointer to the first element of the array.

Syntax:

type arrayName[size];

Examples:

int arr[5]; // Declares an array of 5 integers
char str[10]; // Declares an array of 10 characters

2. Pointer Overview

A pointer is a variable that holds the memory address of another variable. Pointers can be used to reference array elements, traverse arrays, and perform dynamic memory allocation.

Syntax:

type *pointerName;

Examples:

int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character

3. Relationship Between Arrays and Pointers

  • Array Name as Pointer: The name of an array acts as a pointer to its first element.
  • Pointer Arithmetic: Pointers can be used to navigate through array elements.

Examples:

int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];

Explanation:

  • ptr points to the first element of arr.

4. Accessing Array Elements with Pointers

You can use pointers to access and manipulate array elements.

Syntax:

*(pointer + index)

Examples:

#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer to the first element of the array

printf(“First element: %d\n”, *ptr); // Outputs 10
printf(“Second element: %d\n”, *(ptr + 1)); // Outputs 20
printf(“Third element: %d\n”, *(ptr + 2)); // Outputs 30

return 0;
}

Explanation:

  • *ptr dereferences the pointer to get the value of the first element.
  • *(ptr + 1) accesses the second element, and so on.

5. Array and Pointer Arithmetic

You can perform arithmetic operations on pointers to traverse arrays.

Examples:

#include <stdio.h>

int main() {
int arr[4] = {1, 2, 3, 4};
int *ptr = arr;

for (int i = 0; i < 4; i++) {
printf(“Element %d: %d\n”, i, *(ptr + i));
}

return 0;
}

Explanation:

  • ptr + i moves the pointer to the i-th element of the array.

6. Passing Arrays to Functions

When passing arrays to functions, you actually pass pointers to the first element of the array.

Syntax:

void functionName(type *arrayName);

Examples:

#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 arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array to function
return 0;
}

Explanation:

  • printArray function receives a pointer to the first element of the array and its size.

7. Dynamic Memory Allocation with Pointers

Pointers are used with dynamic memory allocation functions to create arrays whose size can be determined at runtime.

Examples:

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

int main() {
int *arr;
int size = 5;

arr = (int *)malloc(size * sizeof(int)); // Allocates memory for an array of 5 integers

if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}

for (int i = 0; i < size; i++) {
arr[i] = i + 1; // Initialize array
}

for (int i = 0; i < size; i++) {
printf(“%d “, *(arr + i)); // Print array elements
}

free(arr); // Free allocated memory
return 0;
}

Explanation:

  • malloc allocates memory dynamically.
  • free deallocates the memory when it is no longer needed.

 

5.7 Array and Pointer

Arrays and pointers are closely related concepts in C programming. They both involve managing collections of data and accessing memory locations. Here’s an in-depth look at how arrays and pointers are interrelated and how they can be used together effectively.


1. Arrays

An array is a collection of elements of the same type stored in contiguous memory locations.

Declaration and Initialization:

type arrayName[size];

Examples:

int arr[5]; // Array of 5 integers
float prices[3] = {10.5, 20.75, 30.0}; // Array of 3 floats initialized
char name[10] = “Alice”; // Array of 10 characters (string)
  • arr[0]: First element.
  • arr[4]: Fifth element.

Accessing Elements:

  • Using Index: arr[index]
  • Using Pointers: *(ptr + index)

2. Pointers

A pointer is a variable that stores the memory address of another variable.

Declaration and Initialization:

type *pointerName;
pointerName = &variable;

Examples:

int x = 10;
int *ptr = &x; // Pointer to the integer variable x
  • *ptr: Dereferences the pointer to access the value of x.

3. Relationship Between Arrays and Pointers

  • Array Name as Pointer: The name of an array is a pointer to its first element.

Example:

int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
  • Accessing Array Elements with Pointers:
    printf(“%d\n”, *(ptr + 0)); // Outputs 1
    printf(“%d\n”, *(ptr + 1)); // Outputs 2
    printf(“%d\n”, *(ptr + 2)); // Outputs 3

4. Pointer Arithmetic with Arrays

You can use pointer arithmetic to navigate through array elements.

Increment and Decrement:

ptr++; // Moves to the next element in the array
ptr–; // Moves to the previous element

Addition and Subtraction:

*(ptr + i) // Accesses the i-th element from the pointer
*(ptr – i) // Accesses the element i positions before the pointer

Example:

int arr[4] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element

printf(“%d\n”, *(ptr + 1)); // Outputs 20
printf(“%d\n”, *(ptr + 2)); // Outputs 30


5. Passing Arrays to Functions

When an array is passed to a function, it is actually passed as a pointer to its first element.

Function Declaration:

void functionName(type *arrayName, int size);

Example:

#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 arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array to function
return 0;
}

Explanation:

  • printArray function receives a pointer to the array and its size.

6. Dynamic Memory Allocation with Pointers

Pointers are used for dynamic memory allocation, allowing arrays to be created with sizes determined at runtime.

Functions:

  • malloc(size_t size): Allocates a block of memory.
  • calloc(size_t num, size_t size): Allocates memory for an array and initializes it to zero.
  • realloc(void *ptr, size_t size): Resizes a previously allocated block of memory.
  • free(void *ptr): Frees previously allocated memory.

Example:

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

int main() {
int *arr;
int size = 5;

arr = (int *)malloc(size * sizeof(int)); // Allocate memory

if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}

for (int i = 0; i < size; i++) {
arr[i] = i + 1; // Initialize array
}

for (int i = 0; i < size; i++) {
printf(“%d “, arr[i]); // Print array elements
}

free(arr); // Free allocated memory
return 0;
}

Explanation:

  • malloc allocates memory dynamically for the array.
  • free deallocates the memory when it is no longer needed.

5.8 String

In C, strings are arrays of characters terminated by a null character ('\0'). Unlike some other programming languages where strings are treated as a built-in data type, in C, strings are managed using arrays of characters.


1. String Declaration and Initialization

String Declaration:

char str[size];

String Initialization:

char str[] = “Hello”;

Examples:

char greeting[6] = “Hello”; // Array of 6 characters including the null terminator
char name[] = “Alice”; // Automatically allocates 6 characters (5 + null terminator)

Explanation:

  • "Hello" includes the null character '\0' at the end, which signifies the end of the string.

2. Accessing String Characters

You can access individual characters of a string using array indexing.

Syntax:

str[index]

Examples:

char str[] = “Hello”;
printf(“%c\n”, str[0]); // Outputs ‘H’
printf(“%c\n”, str[4]); // Outputs ‘o’

Explanation:

  • str[0] accesses the first character.
  • str[4] accesses the fifth character.

3. Common String Functions

The C Standard Library provides several functions for string manipulation in <string.h>.

  • strlen(str): Returns the length of the string (excluding the null terminator).
  • strcpy(dest, src): Copies the source string to the destination string.
  • strcat(dest, src): Appends the source string to the end of the destination string.
  • strcmp(str1, str2): Compares two strings lexicographically.

Examples:

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = “Hello”;
char str2[20] = “World”;

// Length of str1
printf(“Length of str1: %lu\n”, strlen(str1));

// Copy str1 to str2
strcpy(str2, str1);
printf(“str2 after copy: %s\n”, str2);

// Concatenate str1 to str2
strcat(str2, ” World”);
printf(“str2 after concatenation: %s\n”, str2);

// Compare str1 and str2
int result = strcmp(str1, str2);
if (result == 0) {
printf(“str1 and str2 are equal\n”);
} else if (result < 0) {
printf(“str1 is less than str2\n”);
} else {
printf(“str1 is greater than str2\n”);
}

return 0;
}

Explanation:

  • strlen gives the length of the string.
  • strcpy copies str1 to str2.
  • strcat appends " World" to str2.
  • strcmp compares str1 and str2.

4. String Literals

A string literal is a sequence of characters enclosed in double quotes. They are automatically null-terminated.

Example:

char *str = “Hello, World!”;

Explanation:

  • The compiler automatically adds the null terminator.

5. String Input and Output

Input:

  • scanf can be used to read a string. It stops reading at whitespace.

Examples:

char str[50];
printf(“Enter a string: “);
scanf(“%s”, str); // Reads a string until the first whitespace

Output:

  • printf is used to print strings.

Examples:

char str[] = “Hello, World!”;
printf(“%s\n”, str); // Prints the string

6. Strings and Pointers

Strings can be manipulated using pointers. The name of the string is essentially a pointer to the first character.

Example:

#include <stdio.h>

int main() {
char *str = “Hello, Pointer!”;
char *ptr = str;

while (*ptr != ‘\0’) {
printf(“%c”, *ptr);
ptr++;
}

return 0;
}

Explanation:

  • *ptr accesses each character in the string, and ptr++ moves the pointer to the next character.

5.9 String functions in C

C provides a rich set of functions for manipulating strings, which are available in the <string.h> library. These functions are essential for performing various operations on strings, such as copying, concatenation, and comparison. Here’s a comprehensive overview of commonly used string functions:


Here’s a detailed overview of common string functions provided by the C Standard Library in <string.h>. These functions help with various string operations such as copying, concatenating, comparing, and searching.


1. strlen

Prototype:

size_t strlen(const char *str);

Description:

  • Returns the length of the string str, excluding the null terminator.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = “Hello”;
printf(“Length of str: %zu\n”, strlen(str)); // Outputs 5
return 0;
}


2. strcpy

Prototype:

char *strcpy(char *dest, const char *src);

Description:

  • Copies the string src to dest, including the null terminator.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char src[] = “Source”;
char dest[20];

strcpy(dest, src);
printf(“Dest after copy: %s\n”, dest); // Outputs “Source”
return 0;
}


3. strncpy

Prototype:

char *strncpy(char *dest, const char *src, size_t n);

Description:

  • Copies up to n characters from src to dest. If src is shorter than n, dest is padded with null characters.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char src[] = “Hello, World!”;
char dest[20];

strncpy(dest, src, 5);
dest[5] = ‘\0’; // Null-terminate the string
printf(“Dest after copy: %s\n”, dest); // Outputs “Hello”
return 0;
}


4. strcat

Prototype:

char *strcat(char *dest, const char *src);

Description:

  • Appends the string src to the end of dest. The dest string must have enough space to hold the result.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char dest[20] = “Hello”;
char src[] = ” World”;

strcat(dest, src);
printf(“Dest after concatenation: %s\n”, dest); // Outputs “Hello World”
return 0;
}


5. strncat

Prototype:

char *strncat(char *dest, const char *src, size_t n);

Description:

  • Appends up to n characters from src to dest. Null terminates the result.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char dest[20] = “Hello”;
char src[] = ” World!”;

strncat(dest, src, 6); // Appends ” World”
printf(“Dest after concatenation: %s\n”, dest); // Outputs “Hello World”
return 0;
}


6. strcmp

Prototype:

int strcmp(const char *str1, const char *str2);

Description:

  • Compares two strings str1 and str2. Returns 0 if they are equal, a negative value if str1 is less, and a positive value if str1 is greater.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = “Hello”;
char str2[] = “Hello”;

int result = strcmp(str1, str2);
if (result == 0) {
printf(“Strings are equal\n”);
} else if (result < 0) {
printf(“str1 is less than str2\n”);
} else {
printf(“str1 is greater than str2\n”);
}
return 0;
}


7. strncmp

Prototype:

int strncmp(const char *str1, const char *str2, size_t n);

Description:

  • Compares up to n characters of str1 and str2. Returns 0 if they are equal, a negative value if str1 is less, and a positive value if str1 is greater.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = “HelloWorld”;
char str2[] = “Hello”;

int result = strncmp(str1, str2, 5); // Compare first 5 characters
if (result == 0) {
printf(“First 5 characters are equal\n”);
} else {
printf(“First 5 characters are not equal\n”);
}
return 0;
}


8. strchr

Prototype:

char *strchr(const char *str, int c);

Description:

  • Locates the first occurrence of character c in the string str. Returns a pointer to the character, or NULL if not found.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = “Hello World”;
char *ptr = strchr(str, ‘o’);

if (ptr != NULL) {
printf(“Found ‘o’ at position: %ld\n”, ptr – str);
} else {
printf(“‘o’ not found\n”);
}
return 0;
}

9. strrchr

Prototype:

char *strrchr(const char *str, int c);

Description:

  • Locates the last occurrence of character c in the string str. Returns a pointer to the character, or NULL if not found.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = “Hello World”;
char *ptr = strrchr(str, ‘o’);

if (ptr != NULL) {
printf(“Found last ‘o’ at position: %ld\n”, ptr – str);
} else {
printf(“‘o’ not found\n”);
}
return 0;
}


10. strstr

Prototype:

char *strstr(const char *haystack, const char *needle);

Description:

  • Locates the first occurrence of the substring needle in the string haystack. Returns a pointer to the beginning of the found substring, or NULL if not found.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char haystack[] = “Hello World”;
char needle[] = “World”;
char *ptr = strstr(haystack, needle);

if (ptr != NULL) {
printf(“Found substring: %s\n”, ptr);
} else {
printf(“Substring not found\n”);
}
return 0;
}


11. strspn

Prototype:

size_t strspn(const char *str1, const char *str2);

Description:

  • Returns the length of the initial segment of str1 which consists only of characters from str2.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = “abcdef”;
char str2[] = “abc”;

size_t len = strspn(str1, str2);
printf(“Length of initial segment: %zu\n”, len); // Outputs 3
return 0;
}


12. strcspn

Prototype:

size_t strcspn(const char *str1, const char *str2);

Description:

  • Returns the length of the initial segment of str1 which consists of characters not in str2.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = “abcdef”;
char str2[] = “xyz”;

size_t len = strcspn(str1, str2);
printf(“Length of initial segment: %zu\n”, len); // Outputs 6
return 0;
}


13. strtok

Prototype:

char *strtok(char *str, const char *delim);

Description:

  • Tokenizes the string str using the delimiter characters in delim. Returns a pointer to the next token, or NULL if there are no more tokens.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = “Hello,World,Example”;
char *token = strtok(str, “,”);

while (token != NULL) {
printf(“%s\n”, token);
token = strtok(NULL, “,”);
}

return 0;
}

5.10 Pointer and String

In C programming, pointers and strings are closely related. Strings are essentially arrays of characters, and pointers provide a way to manipulate these arrays efficiently. Here’s a detailed look at how pointers and strings interact:

Pointers and Strings

1. String Declaration and Initialization

  • String as an Array of Characters:
    char str[] = “Hello”;
    • str is an array of characters including the null terminator \0.
  • String as a Pointer:
    char *ptr = “Hello”;
    • ptr points to a string literal stored in a read-only section of memory.

2. Accessing String Elements Using Pointers

You can use pointers to access and manipulate individual characters in a string.

Example:

#include <stdio.h>

int main() {
char str[] = “Hello”;
char *ptr = str; // Pointer to the first character of the string

// Accessing elements via pointer
while (*ptr != ‘\0’) {
printf(“%c “, *ptr); // Outputs each character
ptr++; // Move to the next character
}

return 0;
}

3. Modifying Strings Using Pointers

You can use pointers to modify the contents of a string.

Example:

#include <stdio.h>

int main() {
char str[] = “Hello”;
char *ptr = str;

// Modify the string
while (*ptr != ‘\0’) {
*ptr = *ptr + 1; // Increment each character
ptr++;
}

printf(“Modified string: %s\n”, str); // Outputs “Ifmmp”

return 0;
}

4. String Functions Using Pointers

Many standard string functions utilize pointers to process strings.

Examples:

  • strlen: Calculates the length of the string.
    size_t strlen(const char *str);
  • strcpy: Copies a string from one pointer to another.
    char *strcpy(char *dest, const char *src);
  • strcat: Concatenates one string to the end of another.
    char *strcat(char *dest, const char *src);

5. String Comparison Using Pointers

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = “Hello”;
char str2[] = “Hello”;

// Compare strings
if (strcmp(str1, str2) == 0) {
printf(“Strings are equal\n”);
} else {
printf(“Strings are not equal\n”);
}

return 0;
}

6. Using strtok with Pointers

strtok tokenizes a string, returning pointers to each token.

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = “Hello,World,Example”;
char *token = strtok(str, “,”); // Get the first token

while (token != NULL) {
printf(“%s\n”, token); // Print each token
token = strtok(NULL, “,”); // Get the next token
}

return 0;
}

7. Pointer Arithmetic with Strings

Pointer arithmetic allows you to traverse and manipulate strings efficiently.

Example:

#include <stdio.h>

int main() {
char str[] = “Hello”;
char *ptr = str;

// Traverse the string using pointer arithmetic
while (*ptr) {
printf(“%c “, *ptr); // Print each character
ptr++; // Move to the next character
}

return 0;
}

Important Questions
Comments
Discussion
0 Comments
  Loading . . .