Back to C Programming
2026-07-135 min read

Example 4: Strings and Pointers (C Programming)

Learn Example 4: Strings and Pointers (C Programming) step by step with clear examples and exercises.

Why This Matters

Understanding strings and pointers is crucial in C programming as they enable efficient manipulation of text data, which is essential for creating user-friendly interfaces, parsing input, and working with files. Mastering these concepts will not only help you excel in coding interviews but also improve your ability to debug real-world code and write more efficient programs.

Prerequisites

Before diving into strings and pointers, it is essential to have a solid understanding of the following topics:

  • C data types (int, char, float, etc.)
  • Variables and constants
  • Input/Output functions (e.g., printf(), scanf())
  • Basic control structures (if, else, for, while)
  • Arrays in C
  • Pointers basics

Core Concept

Strings in C

A string is an array of characters terminated by a null character (\0). In C, strings are often represented as char arrays. To declare and initialize a string, you can use the following syntax:

char myString[10] = "Hello, World!";

Here, we've created a string called myString, which has a maximum capacity of 10 characters. The string is initialized with "Hello, World!" and ends with the null character (\0).

Pointers in C

A pointer is a variable that stores the memory address of another variable. In C, we can declare pointers using the * symbol. To create a pointer to a char data type, you would do the following:

char *myPointer;

To assign a value to a pointer, we use the address-of operator (&). For example:

char myString[10] = "Hello, World!";
char *myPointer = &myString[0]; // Points to the first character of myString

Now, myPointer points to the memory location where the string starts.

String Functions in C

C provides several library functions for manipulating strings. Some commonly used functions include:

  • strlen(): Returns the length of a string (excluding the null character)
  • strcpy(): Copies one string to another
  • strcmp(): Compares two strings lexicographically
  • strcat(): Concatenates two strings
  • strcmp(): Checks if two strings are equal

Pointer Arithmetic

Pointer arithmetic allows you to manipulate the memory addresses stored in pointers. For example, incrementing a pointer by 1 moves it one data type size ahead (e.g., one char for a char pointer). You can also perform other operations like subtraction and multiplication on pointers.

Dynamic Memory Allocation

Dynamic memory allocation allows you to request memory during runtime. The most common functions for this are malloc() and calloc(). When using these functions, always check if the allocated memory is not NULL before using it to avoid segmentation faults.

Worked Example

Let's create a simple C program that declares and initializes a string, calculates its length using strlen(), copies another string using strcpy(), compares two strings using strcmp(), concatenates two strings using strcat(), and checks if the resulting string is equal to "Hello, World!" using strcmp().

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

int main() {
char myString1[20] = "Welcome";
char myString2[20] = "to the world of C programming!";
char *myResult; // Declare a pointer for the result string

// Allocate memory for the result string and assign it the address of myResult
myResult = (char *)malloc((strlen(myString1) + strlen(myString2) + 1) * sizeof(char));
if (myResult == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Copy the contents of myString1 and myString2 into the result string
strcpy(myResult, myString1);
strcat(myResult, " ");
strcat(myResult, myString2);

// Add a null character at the end of the result string
myResult[strlen(myString1) + strlen(myString2)] = '\0';

if (strcmp(myResult, "Hello, World!") == 0) {
printf("The result is equal to 'Hello, World!'\n");
} else {
printf("The result is not equal to 'Hello, World!'\n");
}

// Free the allocated memory for the result string
free(myResult);

return 0;
}

When you run this program, it will output:

The result is not equal to 'Hello, World!'

Common Mistakes

  • Forgetting the null character (\0) when initializing a string: This can lead to unexpected behavior and segmentation faults.
  • Not checking for memory allocation errors: When using dynamic memory allocation functions like malloc(), always check if the allocated memory is not NULL before using it.
  • Confusing pointers with regular variables: Remember that pointers store memory addresses, not values.
  • Using uninitialized pointers: Always initialize your pointers to NULL or a known address before assigning them a value.
  • Ignoring pointer arithmetic rules: When you increment or decrement a pointer, it moves one data type size ahead (e.g., one char for a char pointer).
  • Not properly freeing allocated memory: Always call free() on dynamically allocated memory when it is no longer needed to avoid memory leaks.

Practice Questions

  1. Write a C program that takes user input and checks if it is a palindrome (reads the same forward and backward).
  2. Create a function that reverses a given string using pointers.
  3. Implement a function that finds the longest common substring between two strings.
  4. Write a C program that counts the number of occurrences of each character in a string.
  5. Write a recursive function that calculates the factorial of a given integer using dynamic memory allocation.
  6. Create a function that sorts an array of integers using bubble sort and dynamically allocates memory for temporary variables.
  7. Implement a linked list data structure and its basic operations (insertion, deletion, traversal) using pointers.

FAQ

What happens if I declare a string without specifying its size?

If you don't specify the size for a string, it will automatically be assigned an array with a length of 1. However, this can lead to buffer overflows and other issues when you try to store larger strings in the array. To avoid these problems, always specify the size of your strings whenever possible.

How do I concatenate two strings using pointers?

To concatenate two strings using pointers, you can allocate memory for the new string, copy the contents of both original strings into the new memory, and then add a null character at the end. However, this method requires manual memory management and is less efficient than using built-in functions like strcat().

Can I use pointers to manipulate arrays other than char arrays?

Yes! Pointers can be used with any data type in C, including integers, floats, and custom data structures. The syntax remains the same: declare a pointer variable using the * symbol and assign it the address of another variable using the address-of operator (&).