C (programming language)

C Program to Find Length of String Using Pointers

Understanding String Length and Pointers

  • String length: The number of characters in a string, excluding the null terminator (\0).
  • Pointers: Variables that store memory addresses, enabling efficient string manipulation.

Key Concepts Involved

  • Pointer Arithmetic: Incrementing a pointer moves it to the next memory address, allowing traversal through string characters.
  • Null Terminator: The character \0 marks the end of a string, essential for determining its length.
  • Dereferencing: Accessing the value stored at a memory address pointed to by a pointer.

Step-by-Step Code Breakdown

  1. Header Inclusion:

C

#include <stdio.h>
  1. Main Function:

C

int main() {
  1. Variable Declaration:

C

char str[100];  // Array to store the string
int len = 0;    // Variable to hold the string length
char *ptr;      // Pointer to the string
  1. User Input for String:

C

printf("Enter a string: ");
fgets(str, 100, stdin);
  1. Pointer Initialization:

C

ptr = str;  // Point ptr to the beginning of the string
  1. Loop to Calculate Length:

C

while (*ptr != '\0') {
    len++;  // Increment length for each non-null character
    ptr++;  // Move pointer to the next character
}
  1. Output the Length:

C

printf("Length of the string: %d\n", len);
  1. Return Statement:

C

return 0;
}

Full Code:

C

#include <stdio.h>

int main() {
    char str[100];
    int len = 0;
    char *ptr;

    printf("Enter a string: ");
    fgets(str, 100, stdin);

    ptr = str;

    while (*ptr != '\0') {
        len++;
        ptr++;
    }

    printf("Length of the string: %d\n", len);

    return 0;
}

Explanation:

  1. stdio.h provides input/output functions.
  2. main is the program’s entry point.
  3. str array stores the string, len holds the length, and ptr points to the string.
  4. User input is stored in str using fgets.
  5. ptr is initialized to point to the start of str.
  6. The while loop iterates until the null terminator is encountered.
  7. In each iteration, len is incremented to count characters, and ptr is moved to the next character.
  8. The final len value represents the string length and is printed.

Conclusion:

This program effectively demonstrates string length calculation using pointers in C. By understanding pointer arithmetic, null terminators, and dereferencing, you can efficiently manipulate strings and explore various string-related tasks in C programming.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button