← C roadmap

Topic 5 of 15 · Intermediate

Arrays & Strings

1D/2D arrays, null-terminated strings and string.h.

Concept

An array is a fixed block of same-type elements in contiguous memory. C doesn't check bounds — going past the end is undefined behaviour.

A string is a char array ending in '\0'. Its length (strlen) excludes the terminator, so size it one larger.

Use strcpy/strncpy, strcat, strcmp and strlen from <string.h>. Prefer fgets over the dangerous gets for input.

Code (C17)

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

int main(void) {
    int marks[5] = {78, 92, 65, 88, 70};
    int sum = 0;
    for (int i = 0; i < 5; i++) sum += marks[i];
    printf("avg = %.1f\n", sum / 5.0);

    int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("%d\n", grid[1][2]);  // 6

    char name[20];
    fgets(name, sizeof name, stdin);
    name[strcspn(name, "\n")] = '\0';
    printf("Hello %s (%zu chars)\n", name, strlen(name));
    return 0;
}

Remember

  • No bounds checking in C.
  • Strings end with '\0'.
  • Never use gets().

Interview questions

Reverse a string in place.

Use two indices i = 0 and j = strlen − 1, swap s[i] and s[j], move inward until they meet.

sizeof vs strlen on a char array?

sizeof gives the array's total bytes (including '\0' and unused space); strlen counts characters before '\0'.

Practise C with the AI mentor

Lesson test

Take an 8-question test on “Arrays & Strings” — concepts, output prediction, bug spotting and interview questions.

Can't find a C topic you need for exams or placements? Request it and we'll add it.