← कोर्स पर वापस जाएँ: C programming from scratch

Strings: char arrays and the null terminator

वीडियो जल्द आ रहा है

C has no string type of its own. A string is an array of char whose end is marked with the null character '\0', a byte with value zero. All the text functions of the library rely on that terminator to know where the string ends. Understanding this explains almost every text error in C: sizes that do not add up, unterminated strings and overflows.

Declaring strings

Writing char name[] = "Ana"; makes the compiler create an array of 4 bytes: 'A', 'n', 'a' and '\0'. The literal takes one byte more than its letters. If you reserve a fixed size, such as char name[20], 19 letters fit plus the terminator. Distinguish two things: char s[] = "hello" creates a modifiable copy, while const char *p = "hello" points to a read-only literal; modifying it is undefined behavior, which is why you should always declare it with const.

c
#include <stdio.h>

int main(void) {
    char name[] = "Ana";             /* 4 bytes with '\0' */
    char buffer[20] = "Hi";          /* rest filled with zeros */
    const char *greeting = "Hello";  /* read-only literal */

    printf("sizeof(name) = %zu\n", sizeof(name));     /* 4 */
    printf("sizeof(buffer) = %zu\n", sizeof(buffer)); /* 20 */

    name[0] = 'E';                   /* fine: our own copy */
    printf("%s, %s, %s\n", name, buffer, greeting);

    for (int i = 0; name[i] != '\0'; i++) {
        printf("%c-", name[i]);
    }
    printf("\n");
    return 0;
}

Reading lines with fgets

The right function to read a line with spaces is fgets(buffer, size, stdin). It reads at most size - 1 characters, always adds the terminator and never overflows. If it fits, it keeps the final newline, which you normally want to remove. It returns NULL if it could not read anything (end of input). It is the safe alternative to gets and to scanf("%s") without a limit.

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

int main(void) {
    char line[64];

    printf("Your full name: ");
    if (fgets(line, sizeof(line), stdin) == NULL) {
        return 1;
    }
    line[strcspn(line, "\n")] = '\0';   /* remove the newline if present */

    printf("Hello, %s! (%zu characters)\n", line, strlen(line));
    return 0;
}

strcspn(line, "\n") returns the position of the first newline, or the total length if there is none; putting a '\0' there trims the string safely in both cases. If the line was longer than the buffer, the rest stays unread in the input and will affect the next read: in serious programs that leftover is discarded.

Working character by character

Since a string is an array, you can walk it up to the terminator. The <ctype.h> header offers functions such as isalpha, isdigit, toupper and tolower to classify and convert characters. Always pass values that fit in unsigned char; with negative values the behavior is undefined, so cast if your char is signed.

c
#include <ctype.h>
#include <stdio.h>

static void count_kinds(const char *text, int *letters, int *digits) {
    *letters = 0;
    *digits = 0;
    for (size_t i = 0; text[i] != '\0'; i++) {
        unsigned char ch = (unsigned char)text[i];
        if (isalpha(ch)) {
            (*letters)++;
        } else if (isdigit(ch)) {
            (*digits)++;
        }
    }
}

int main(void) {
    char word[] = "c17 rocks 2024";
    for (size_t i = 0; word[i] != '\0'; i++) {
        word[i] = (char)toupper((unsigned char)word[i]);
    }
    int letters, digits;
    count_kinds(word, &letters, &digits);
    printf("%s -> %d letters, %d digits\n", word, letters, digits);
    return 0;
}

Common mistakes: the null character and comparison

A string of n letters needs n + 1 bytes because it ends with '\0'. Declaring char word[5] = "hello"; leaves no room for the terminator: string functions will keep reading neighbouring memory until they find a zero. Write char word[] = "hello"; and let the compiler compute 6 bytes. Another very frequent mistake is comparing strings with ==: that compares memory addresses, not the text, and it is almost always false. To know whether two strings are equal use strcmp(a, b) == 0, and to copy use functions with a limit, never a direct assignment to an array.

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

int main(void) {
    char word[] = "hello";          /* 6 bytes: five letters plus '\0' */
    char other[] = "hello";
    printf("%zu\n", strlen(word));  /* 5: strlen does not count '\0' */
    printf("%d\n", (const void *)word == (const void *)other); /* 0: different addresses */
    printf("%d\n", strcmp(word, other) == 0); /* 1: same text */
    return 0;
}

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →