What are Arrays of Strings in C- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Arrays of Strings in C

Chapter 9, Strings: store many strings in a two-dimensional character array, understand its memory layout, then test yourself with a quiz and interview questions. Free embedded C course by EmbeddedPathashala.

An array of strings in C is the natural way to keep a list of names, commands or states, and it is one of the most common data structures in embedded C programming. In this final lecture of the Strings chapter of our free C programming course you will build a two-dimensional character array, see exactly how it sits in memory, avoid its classic traps, and finish with a ten-question quiz and ten interview questions with answers.

Topics in This Lecture

array of strings in C 2D char array C programming quiz C interview questions free C programming course free embedded C course c programming for embedded systems

What You Will Learn

  • How to declare and initialise a two-dimensional array of characters.
  • How rows, columns and terminators are laid out in memory.
  • How to read and print each string, and how strlen and sizeof differ here.
  • The common mistakes with row width and assignment.
  • How well you have understood the whole chapter, through a quiz and interview practice.

Prerequisites

You should be comfortable with one-dimensional arrays, two-dimensional arrays from the Arrays chapter, the null terminator, and the string functions covered earlier in this chapter.

What Is an Array of Strings in C?

Since a string is already an array of characters, a list of strings is an array of those arrays, which means a two-dimensional array of char. The first size is the number of strings, and the second size is the width of every row. Each row is one complete string with its own terminator. Here is a table of four task states, written the way a small scheduler might keep them:

char state[4][8] = { "idle", "run", "sleep", "fault" };

Every row has exactly eight bytes. That width must be at least the longest string plus one, and here the longest is “sleep” or “fault” with five letters, so eight is comfortable. Shorter strings are padded with zero bytes up to the row width, because the compiler fills the rest of an initialised array with zeros.

Memory Grid of char state[4][8]

Row01234567
state[0]idle\0\0\0\0
state[1]run\0\0\0\0\0
state[2]sleep\0\0\0
state[3]fault\0\0\0

The rows sit one after another in a single block of 32 bytes. This is called row-major order. The array name state refers to the whole block, while state[2] is the third row, which behaves as a string in its own right.

Accessing Strings in a 2D Char Array

ExpressionMeaningExample result
state[2]Third row, usable as a string“sleep”
state[2][1]Second character of the third row‘l’
sizeof state[2]Bytes in one row8
sizeof stateBytes in the whole array32
strlen(state[2])Characters before the terminator5

Complete Program: Printing Every Row

Save this original example as ep_states.c. It loops over the rows and prints the text, the real string length and the row width, so you can see the difference between those three numbers:

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

int main(void)
{
    char state[4][8] = { "idle", "run", "sleep", "fault" };

    for (int i = 0; i < 4; i++)
        printf("%d -> %-6s len %zu, row bytes %zu\n",
               i, state[i], strlen(state[i]), sizeof state[i]);

    printf("total bytes: %zu\n", sizeof state);
    printf("state[2][1] = %c\n", state[2][1]);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_states ep_states.c
$ ./ep_states
0 -> idle   len 4, row bytes 8
1 -> run    len 3, row bytes 8
2 -> sleep  len 5, row bytes 8
3 -> fault  len 5, row bytes 8
total bytes: 32
state[2][1] = l

The format %-6s left-aligns each name in a field of six characters so the columns line up. Notice the gap between the text length and the row width. In this example 17 of the 32 bytes carry real characters, and the rest is padding and terminators.

Rules and Traps with a 2D Array of Strings

  • The row width must include the terminator. If the longest string has n characters, the width must be at least n + 1.
  • A row cannot be assigned with an equals sign. state[1] = "wait"; is a compile error, because a row is an array. Use a copy function with a size check instead.
  • A too-narrow row breaks the string. A row with exactly as many bytes as characters has no terminator, and printf will read into the next row.
  • Memory is wasted on short strings. Every row costs the full width, so one very long entry makes all rows expensive.
  • Passing to a function needs the column count. A parameter written as char list[][8] keeps the row width, which the compiler needs to find each row.

Warning: the fixed row width is the price of simplicity. When the strings are constant, an array of pointers to literals stores no padding and saves RAM. That structure is the subject of the next chapter section on arrays of pointers.

Real-World Use Cases

  • State and event names for logging in a state machine.
  • Menu items on a small LCD or a serial console.
  • Command tables where each row holds a keyword that a parser matches.
  • Storing a short list of user-entered names, such as paired device labels, in fixed slots.

Best Practices, Performance and Security

  • Define the row width and the row count as named constants, never as repeated numbers.
  • Choose the width from the longest string plus one, and recheck it whenever you add an entry.
  • When filling a row at run time, use a bounded copy with the row width as the limit.
  • Access rows through a checked index. An index outside the array reads or writes unrelated memory.
  • Remember that a 2D array is one contiguous block, so it has excellent cache and DMA behaviour, but it is not resizable.

Chapter Quiz: Test Your Strings Knowledge

Answer each question first, then open the answer. All programs assume a typical 64-bit computer unless stated.

  1. Given char s[8] = "run";, what does sizeof s return?

    • A) 3
    • B) 4
    • C) 8
    • D) Undefined
    Show answer

    C) 8. sizeof counts every element of the array, not just the text.

  2. For the same array, what does strlen(s) return?

    • A) 3
    • B) 4
    • C) 8
    • D) 7
    Show answer

    A) 3. strlen counts characters before the terminator.

  3. Given const char *p = "abc";, what is the result of p[0] = 'X';?

    • A) p becomes “Xbc”
    • B) Compile error only
    • C) Undefined behaviour
    • D) p becomes NULL
    Show answer

    C) Undefined behaviour. With const the compiler will normally reject it, and without const it may crash at run time.

  4. Which statement is invalid for char a[] = "on";?

    • A) a[0] = ‘O’;
    • B) a = “off”;
    • C) strlen(a);
    • D) sizeof a;
    Show answer

    B) a = “off”; An array name is not assignable.

  5. What is sizeof state for char state[4][8]?

    • A) 8
    • B) 12
    • C) 32
    • D) 4
    Show answer

    C) 32. Four rows of eight bytes each.

  6. Which array holds “fault” as a proper string?

    • A) char a[4]
    • B) char a[5]
    • C) char a[6]
    • D) None of them
    Show answer

    C) char a[6]. Five letters plus the terminator need six bytes. Size 5 would fill the array but leave no terminator.

  7. What does strcat(dst, src) return?

    • A) The length of dst
    • B) The pointer dst
    • C) The pointer to the end of dst
    • D) Nothing
    Show answer

    B) The original pointer dst.

  8. When does the loop while ((*d++ = *s++) != '\0'); stop?

    • A) Before copying the terminator
    • B) After copying the terminator
    • C) After copying 255 bytes
    • D) Never
    Show answer

    B) After the terminator has been copied, because the loop tests the value just stored.

  9. What happens if the destination of strcpy is too small?

    • A) The copy is shortened automatically
    • B) An error code is returned
    • C) Buffer overflow, undefined behaviour
    • D) The compiler adds space
    Show answer

    C) Buffer overflow with undefined behaviour. The function cannot know the buffer size.

  10. On a 32-bit microcontroller, what does sizeof (const char *) give?

    • A) 1
    • B) 2
    • C) 4
    • D) 8
    Show answer

    C) 4. A pointer is as wide as an address, which is 32 bits on such devices.

C Interview Questions on Strings

These questions appear regularly in interviews for embedded and firmware roles. Speak your answer aloud before opening it.

  1. What is the difference between char s[] = “hi” and const char *s = “hi”?

    Show answer

    The array owns a writable copy of the text, and its size includes the terminator. The pointer refers to a read-only literal and occupies only the space of an address. The array name cannot be reassigned, but the pointer can.

  2. Why is strcpy considered unsafe?

    Show answer

    It has no parameter for the destination size, so it copies until the source terminator regardless of space. Oversized input overflows the buffer and can corrupt memory or enable an exploit.

  3. Write strcpy using pointers.

    Show answer

    Save the start of the destination, loop with while ((*dst++ = *src++) != ‘\0’) and an empty body, then return the saved start.

  4. Why does strcat return the destination pointer?

    Show answer

    So calls can be nested, as in strcat(strcat(a, b), c). The inner call finishes first and passes the same buffer outward.

  5. What does *p++ do?

    Show answer

    Postfix increment binds tighter, so it means *(p++). It uses the value at the current address and then advances the pointer.

  6. Why is sizeof on a function parameter declared as char buf[] wrong for finding the length?

    Show answer

    An array parameter is adjusted to a pointer, so sizeof returns the pointer size. Pass the capacity as a separate argument.

  7. Where are string literals stored, and why use const char * for them?

    Show answer

    Typically in a read-only section, which on a microcontroller is flash. Modifying them is undefined behaviour, so const lets the compiler reject accidental writes.

  8. Why can repeated strcat calls be slow?

    Show answer

    Each call scans from the start of the destination to find its end. Many appends repeat that scan, so the cost grows quickly. Track the end position yourself or use snprintf with an offset.

  9. Why does strncpy not always give a valid string?

    Show answer

    When the source is as long as or longer than the limit, strncpy does not write a terminator. It also pads short strings with zeros, which wastes time. Always terminate the destination manually, or use a bounded helper.

  10. How is a 2D char array laid out in memory?

    Show answer

    As one contiguous block in row-major order. Each row has the same fixed width, and shorter strings are padded with zero bytes up to that width.

Summary and Key Takeaways

  • An array of strings is a 2D char array with the width of every row fixed at compile time.
  • Each row is a complete string, so the width must cover the longest text plus one.
  • Rows cannot be assigned with an equals sign, and they need a copy function with a size check.
  • sizeof gives bytes, strlen gives characters, and they are rarely equal.
  • Strings chapter recap: copy, concatenate, compare sizes, own your memory, and never trust an unbounded call.

Conclusion

You have now covered the full toolkit for working with strings in this free C programming course: copying, joining, array versus pointer storage, safe pointer use and collections of strings. Each lecture came back to the same idea, which is that C gives you raw memory and expects you to manage its size. That mindset is at the heart of C programming for embedded systems. Use the quiz and the interview questions for revision, then continue to the next chapter of the free embedded C course.

Frequently Asked Questions

How do I declare an array of strings in C?

Use a two-dimensional char array, for example char names[4][8] = { “a”, “bb”, “ccc”, “dddd” };, where the second size must hold the longest string plus the terminator.

How do I print every string in a 2D char array?

Loop over the first index and print each row with the %s specifier, for example printf(“%s\n”, names[i]);.

Why can I not assign a new string to a row of the array?

A row is an array, and arrays are not assignable. Copy the characters with a bounded copy function instead.

What is the difference between a 2D char array and an array of char pointers?

The 2D array stores all characters in one block with a fixed row width. The pointer array stores only addresses and can refer to strings of different lengths, usually literals.

How much memory does a 2D char array use?

Rows multiplied by the row width, regardless of how long each string really is.

Chapter Complete: Keep Learning for Free

You finished another chapter of this free C tutorial. Review the quiz, share the course with a friend who wants a free embedded C course, and continue to the next chapter.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →