🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Arrays and strings: char arrays and '\0'

Keep measurements in arrays and find the element count with sizeof; understand the '\0' at the end of text in C, and use strlen, strcmp and snprintf to handle strings safely.

An energy analyser measures power every hour throughout the day; at the end of the day you have 24 values. Keeping them in 24 separate variables called g1, g2, … is tiring and can't be processed with a loop. An array is a set of numbered boxes that hold values of the same type side by side in memory. In C, text is actually an array too: an array of characters. We'll look at both together in this lesson, because a large share of C's security holes are born right here, at array boundaries.

Defining and walking through an array

#include <stdio.h>

int main(void) {
    double guc_kw[6] = {1.2, 2.8, 3.5, 3.1, 2.0, 0.9};
    int n = sizeof(guc_kw) / sizeof(guc_kw[0]);
    double enerji = 0.0;
    int tepe = 0;

    for (int i = 0; i < n; i++) {
        enerji += guc_kw[i];          // her olcum 1 saat
        if (guc_kw[i] > guc_kw[tepe]) tepe = i;
    }
    printf("Olcum sayisi: %d\n", n);
    printf("Toplam enerji: %.1f kWh\n", enerji);
    printf("Tepe: %d. saat, %.1f kW\n", tepe + 1, guc_kw[tepe]);
    return 0;
}
Olcum sayisi: 6
Toplam enerji: 13.5 kWh
Tepe: 3. saat, 3.5 kW
  • double guc_kw[6]: reserves room for 6 doubles. The size must be a constant known at compile time.
  • Indices start at 0: the first element is guc_kw[0], the last is guc_kw[5].
  • sizeof(guc_kw) / sizeof(guc_kw[0]): divides the array's total size in bytes by the size of one element, giving the element count (48 / 8 = 6). If you add elements to the array, the loop adapts automatically.
  • If you write int a[5] = {1, 2}; the remaining elements become 0. You can't assign one array to another with =; you have to copy the elements in a loop.

Since each measurement is the average power over one hour, adding up the powers gives the energy directly in kWh.

Strings: char arrays ending in '\0'

C has no separate "text" type. Text is a char array with a '\0' (the "null character", whose value is zero) added at the end. printf and the string functions find where the text ends by looking for this character.

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

int main(void) {
    char etiket[] = "PANO1";

    printf("Metin : %s\n", etiket);
    printf("sizeof: %zu\n", sizeof(etiket));
    printf("strlen: %zu\n", strlen(etiket));
    printf("Son karakter kodu: %d\n", etiket[5]);

    etiket[4] = '2';
    printf("Degisti: %s\n", etiket);
    return 0;
}
Metin : PANO1
sizeof: 6
strlen: 5
Son karakter kodu: 0
Degisti: PANO2
Index012345
Content'P''A''N''O''1''\0'

A 5-letter text takes 6 bytes. strlen counts the characters up to '\0' (5); sizeof gives the total size of the array in memory (6). When you reserve room for text, always think one more.

Safe copying: snprintf instead of strcpy

strcpy(hedef, kaynak) copies the source up to '\0' but never looks at the size of the destination. If the source is long, it overwrites the memory beyond the destination. This "buffer overflow" leads to both crashes and security holes. The safer route is snprintf: it takes the size of the destination, never writes more than that and guarantees a '\0' at the end.

#include <stdio.h>

int main(void) {
    char kisa[6];
    char uzun[] = "SICAKLIK";

    // strcpy(kisa, uzun);  // TEHLIKE: 9 bayt, 6 baytlik yere yazilirdi!
    int gereken = snprintf(kisa, sizeof(kisa), "%s", uzun);

    printf("kisa: %s\n", kisa);
    printf("Gereken uzunluk: %d\n", gereken);
    if (gereken >= (int)sizeof(kisa)) {
        printf("Uyari: metin kirpildi\n");
    }
    return 0;
}
kisa: SICAK
Gereken uzunluk: 8
Uyari: metin kirpildi

snprintf returns how many characters it would have written if there had been enough room (8). If that value is equal to or larger than the destination size, the text was truncated. If you must use strcpy, first make sure there is room: if (strlen(kaynak) < sizeof(hedef)) strcpy(hedef, kaynak);. strncpy is not as safe as people think: if the source is too long, it doesn't put a '\0' at the end.

Comparing and joining text

You can't compare two strings with ==; that compares their addresses in memory, not their contents. Use strcmp instead: it returns 0 if the strings are the same. You'll use this pattern a lot when decoding a command that arrives over a serial port.

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

int main(void) {
    char komut[] = "START";
    char mesaj[32];

    if (strcmp(komut, "START") == 0) {
        snprintf(mesaj, sizeof(mesaj), "Motor %d: %s (%.1f A)", 2, "calisiyor", 7.5);
    } else {
        snprintf(mesaj, sizeof(mesaj), "Bilinmeyen komut: %s", komut);
    }
    printf("%s\n", mesaj);
    printf("Mesaj uzunlugu: %zu\n", strlen(mesaj));
    return 0;
}
Motor 2: calisiyor (7.5 A)
Mesaj uzunlugu: 26

snprintf knows all of printf's formats, so using it to build text instead of chains of strcat is both safe and readable. Put a limit on text read from the user as well: scanf("%19s", ad) writes at most 19 characters into a 20-byte array.

Common mistakes

Going past the end of an array: C doesn't check whether an access like dizi[10] is valid. An overflow sometimes crashes right away, sometimes corrupts another variable, and the bug shows up much later.

  • Leaving no room for '\0': char e[5] is not enough for "PANO1"; you need 6.
  • Comparing strings with ==: always use strcmp(a, b) == 0.

Exercise

The temperatures of three sensors are in an array: 21.5, 22.0, 23.4. In a loop, use snprintf to build a label for each sensor in the form SENSOR_01, SENSOR_02… (into a 16-byte char array) and print it as SENSOR_01 -> 21.5 C.

Hint: %02d pads a number to two digits with zeros. Use i + 1 for the sensor number.

Solution

#include <stdio.h>

int main(void) {
    double sicaklik[3] = {21.5, 22.0, 23.4};
    char etiket[16];

    for (int i = 0; i < 3; i++) {
        snprintf(etiket, sizeof(etiket), "SENSOR_%02d", i + 1);
        printf("%s -> %.1f C\n", etiket, sicaklik[i]);
    }
    return 0;
}
SENSOR_01 -> 21.5 C
SENSOR_02 -> 22.0 C
SENSOR_03 -> 23.4 C

You've learned about arrays, text that ends in '\0' and safe string handling. In the next lesson we enter C's most powerful and most feared topic, pointers; there you'll see how arrays really work.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. For char ad[] = "ABC"; what is sizeof(ad)?
2. What does strcmp("START", "START") return?
3. What is the valid index range of the array int olcum[5];?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.