C Language Pointers, Arrays, and String Functions Mastery

C Language: Pointers, Arrays, and String Operations

In the C language, pointers and arrays share a very close relationship. Understanding this connection is crucial for effective memory handling and efficient programming.

An array is a collection of similar data items stored in contiguous memory locations. A pointer, conversely, is a variable that stores the memory address of another variable. Since an array name represents the address of its first element, a pointer can be directly used to access and manipulate array elements.

1. Array Name as a Pointer

In C, the name of an array behaves like a constant pointer.

For example, if we declare: int arr[5];

Here, arr contains the memory address of arr[0]. This means:

arr ≡ &arr[0]

Thus, the array name itself acts like a pointer pointing to the first element.

2. Accessing Array Elements Using Pointer Notation

Since an array name acts like a pointer, we can access array elements using pointer expressions.

For example: *(arr + i) is the same as arr[i]

This demonstrates that pointer notation and array subscript notation are interchangeable. This relationship confirms that arrays internally depend on pointer arithmetic.

3. Pointer Arithmetic and Arrays

Pointers can be increased or decreased to access array elements because array elements are stored sequentially in memory. Pointer arithmetic adjusts based on the size of the data type.

For example, if an integer occupies 2 bytes and the base address is 1000:

  • Pointer + 1 moves to address 1002
  • Pointer + 2 moves to address 1004

This sequential movement simplifies array processing using pointers.

4. Memory Representation

Arrays occupy a block of continuous memory. When a pointer is assigned the array name, it points to the starting address of this memory block. By incrementing the pointer value using pointer arithmetic, it moves to the next memory location storing the next array element. Pointers thus allow direct access to these memory locations without using subscripts.

Example Representation:

ElementAddress
arr[0]1000
arr[1]1002
arr[2]1004

The pointer at address 1000 can access all these elements through arithmetic operations.

5. Importance of the Pointer–Array Relationship

The relationship between pointers and arrays is vital for several reasons:

  1. Efficient Access: Pointers often provide faster access to array elements than using subscripts.
  2. Function Communication: Arrays are automatically passed to functions as pointers, which saves memory and facilitates large data transfer.
  3. Dynamic Memory Management: Only pointers can access memory allocated at runtime using malloc() or calloc(), making them essential for dynamic arrays.
  4. Complex Data Structures: Many structures like linked lists, trees, and graphs rely heavily on pointers.
  5. Compact Code: Using pointer notation can reduce code size and improve readability in certain contexts.

C String Handling Functions

In C programming, strings are stored as a sequence of characters terminated by a null character ('\0'). The string.h header file provides useful functions for common string operations like finding length, copying, comparing, and joining strings.

1. strlen() – String Length

Definition: strlen() calculates the total number of characters in the string, excluding the null character (\0).

Syntax: int strlen(string);

Working:

  • Starts counting from index 0.
  • Counts each character.
  • Stops upon finding '\0'.
  • Returns the final count.

Example:

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

int main() {
    char name[20] = "Rohit";
    int len = strlen(name);
    printf("Length = %d", len);
    return 0;
}

Output: Length = 5

2. strcpy() – String Copy

Definition: strcpy() copies the entire contents of the source string into the destination string, including the null character.

Syntax: strcpy(destination, source);

Working:

  • Copies characters from source to destination sequentially.
  • Appends \0 automatically at the end.

Example:

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

int main() {
    char src[20] = "Hello";
    char dest[20];
    strcpy(dest, src);
    printf("Copied String: %s", dest);
    return 0;
}

Output: Copied String: Hello

3. strcmp() – String Compare

Definition: strcmp() compares two strings character by character and returns:

  • 0 → if both strings are exactly the same.
  • Positive value → if the first string is lexicographically greater.
  • Negative value → if the first string is lexicographically smaller.

Syntax: strcmp(string1, string2);

Working:

  • Compares the ASCII values of characters.
  • If a mismatch occurs, it returns the difference of the ASCII values of the first unmatched characters.
  • If all characters match, it returns 0.

Example:

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

int main() {
    int result = strcmp("apple", "banana");
    printf("Result = %d", result);
    return 0;
}

Output: Result = -1 (Explanation: “apple” comes before “banana” alphabetically.)

4. strcat() – String Concatenation (Joining)

Definition: strcat() joins (appends) the second string to the end of the first string.

Syntax: strcat(string1, string2);

Working:

  • Moves to the null terminator (end) of string1.
  • Starts copying characters from string2.
  • Adds a new \0 at the very end.

Example:

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

int main() {
    char s1[30] = "Hello ";
    char s2[20] = "World";
    strcat(s1, s2);
    printf("%s", s1);
    return 0;
}

Output: Hello World

Array of Strings in C

An array of strings in C is a collection of multiple strings stored together using an array structure. Since a string in C is fundamentally a character array, an array of strings means an array of character arrays.

In simple terms, an array of strings = multiple strings stored together.

An array of strings is declared as: char name[rows][columns];

  • rows → the number of strings to store.
  • columns → the maximum length of each string (including \0).

For example, to store 5 names, each up to 20 characters long:

char names[5][20];

How It Works:

  • Each row stores one complete string.
  • Characters are stored sequentially until the '\0' (null character) is reached.
  • All strings are stored in contiguous memory blocks.

Advantages:

  1. Useful for storing lists of words, such as names, cities, or fruits.
  2. Easy access to each string using a simple index (e.g., fruits[i]).
  3. Simplifies managing and processing multiple strings concurrently.
  4. Easier to pass as a single unit to functions for processing.

Example Program:

#include <stdio.h>

int main() {
    char fruits[3][20] = {"Apple", "Banana", "Mango"};
    for(int i = 0; i < 3; i++) {
        printf("%s\n", fruits[i]);
    }
    return 0;
}

Output:

Apple
Banana
Mango