Karnataka KSEAB SSLC JTS Programming in ANSI C study materials
Karnataka KSEAB SSLC JTS Programming in ANSI C study resources

Karnataka KSEAB SSLC JTS Programming in ANSI C: Arrays and Strings: One- and Two-Dimensional Arrays, String Handling and Standard String Functions

Karnataka KSEAB SSLC JTS Programming in ANSI C · Work through your exam, one topic at a time.

All guide sections

Arrays and Strings: One- and Two-Dimensional Arrays, String Handling and Standard String Functions

This domain tests contiguous storage: how arrays are indexed and laid out in memory, why C strings need a terminator, and which <string.h> calls to reach for.

One- and two-dimensional arrays

int a[5]; reserves five contiguous ints with indices 0 to 4, and C performs no bounds checking. int a[5] = {1, 2}; zero-fills the remaining elements, and int a[] = {1, 2, 3}; sizes itself to 3. A two-dimensional array int m[3][4]; is an array of three arrays of four ints, stored row by row: m[1][2] sits at offset (1*4 + 2) * sizeof(int) from m. When an array is passed to a function it decays to a pointer, so the function also needs the dimensions: void show(int m[][4], int rows).

Strings

A C string is a char array ending with '\0'. char s[] = "KSEAB"; has six elements, but strlen(s) is 5. char *p = "KSEAB"; points at a string literal, which must not be written to. <string.h> supplies strlen, strcpy/strncpy, strcat/strncat, strcmp, strchr, strstr and memset.

Worked example

char s[] = "C";
printf("%zu %zu\n", sizeof s, strlen(s));

This prints 2 1: sizeof counts the terminator, strlen does not. Likewise strcmp("abc", "abd") returns a negative value because 'c' < 'd', and equal strings return 0.

Traps

  • Using == on strings compares addresses; use strcmp.
  • strcat requires the destination to hold both strings plus '\0'.
  • Copying into a string literal is undefined behaviour.
  • An index outside 0 to n-1 compiles fine and corrupts memory.
  • scanf("%s", buf) can overflow; give a width such as %19s.