C Strings Interview Questions- C Programming Course For Engineering Students

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Chapter 9 · Lecture 7 of 7

C Strings Interview Questions

A command-matcher lab, a verified quiz and fourteen interview questions with answers to close the Strings chapter.

9
Chapter: Strings
7/7
Lecture in this chapter
Free
Always, for every student

What You Will Learn

  • How to combine literals, writable buffers, uppercase conversion and table lookup in one small program
  • How a command table of string pointers drives a serial console in embedded C programming
  • Eight multiple-choice questions and ten output-prediction questions with verified answers
  • Three programming challenges to practise string loops
  • Fourteen C strings interview questions with model answers
  • A recap of the whole Strings chapter

Prerequisites

  • Lectures 1 to 6 of this chapter
  • Functions, arrays and pointers from the earlier chapters

This is the final lecture of the Strings chapter in the free C programming course. First you build a small command matcher, the kind of code that sits behind a serial console on a real device. Then you test yourself with a quiz, and finish with a set of C strings interview questions and answers that employers use to separate people who memorised syntax from people who understand memory. If you have followed this free embedded C course from the start, you already know everything you need.

Lab: Build a Serial Command Matcher

Many embedded devices accept short text commands over a UART: LED ON, LED OFF, STATUS. Users type them in any letter case, so the firmware normalises the text, looks it up in a table and acts on the result. The program below does exactly that, using only ideas from this chapter.

Data flow of the command matcher

Literal input → Copy to writable buffer → Convert to uppercase → Compare with table → Command id or unknown

Save it as cmd_lab.c:

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

static const char *const cmd_table[] = {"LED ON", "LED OFF", "STATUS"};
#define CMD_COUNT (sizeof cmd_table / sizeof cmd_table[0])

static void to_upper(char *s)
{
    for (; *s != '\0'; s++)
        if (*s >= 'a' && *s <= 'z')
            *s = (char)(*s - 'a' + 'A');
}

static int find_command(const char *text)
{
    for (size_t i = 0; i < CMD_COUNT; i++)
        if (strcmp(text, cmd_table[i]) == 0)
            return (int)i;
    return -1;
}

int main(void)
{
    const char *inputs[] = {"led on", "Status", "reboot"};

    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++) {
        char buf[16];                                  /* writable copy */
        snprintf(buf, sizeof buf, "%s", inputs[i]);
        to_upper(buf);

        int id = find_command(buf);
        if (id >= 0)
            printf("\"%s\" -> %s -> command %d\n", inputs[i], buf, id);
        else
            printf("\"%s\" -> %s -> unknown\n", inputs[i], buf);
    }
    return 0;
}
gcc -std=c17 -Wall -Wextra -o cmd_lab cmd_lab.c
./cmd_lab

Expected output:

"led on" -> LED ON -> command 0
"Status" -> STATUS -> command 2
"reboot" -> REBOOT -> unknown

Why the program is built this way

  • cmd_table is an array of pointers to literals, declared const twice so neither the pointers nor the text can change. The table lives in flash.
  • The inputs are literals, which cannot be edited, so each one is copied into the writable array buf with snprintf. This is the pattern from Lecture 3 and Lecture 4 together.
  • to_upper walks the string with a pointer until the terminator, exactly as in Lecture 5, and changes only lowercase letters.
  • find_command uses strcmp, never ==, because content, not address, matters (Lecture 2).
  • CMD_COUNT divides the size of the table by the size of one element, so adding a command needs no other edit.
Input typedAfter uppercaseResult
led onLED ONcommand 0
StatusSTATUScommand 2
rebootREBOOTunknown

Chapter 9 Recap: What You Learned in C Strings

LectureTopicOne-line takeaway
1Strings and the NUL terminatorA string is a char array ended by a zero byte
2String literalsA literal is an array that decays to a pointer; == compares addresses
3Literal rulesNever modify a literal; ‘b’ and “b” differ; escapes and concatenation
4String variablesCapacity is text length plus one; sizeof is not strlen
5TraversalLoop until the terminator, by index or by pointer
6Input and output%s stops at whitespace; use widths and fgets

C Strings Quiz: Multiple Choice

Pick an answer first, then open the box to check it.

  1. Which byte ends a C string?

    • A. '0'
    • B. '\0'
    • C. NULL
    • D. EOF
    Show answer

    Answer: B. The terminator is the character with value 0, written '\0'. '0' is the digit with value 48, and NULL is a pointer constant.

  2. What does sizeof("UART") evaluate to?

    • A. 4
    • B. 5
    • C. 8
    • D. It depends on the pointer size
    Show answer

    Answer: B. A literal is an array of five chars: four letters and the terminator. sizeof on the literal itself does not use the pointer size.

  3. Which declaration lets you safely change the text later?

    • A. char *p = "hi";
    • B. const char *p = "hi";
    • C. char a[] = "hi";
    • D. char *p = &"hi";
    Show answer

    Answer: C. Only the array form gives you a private, writable copy. A and B point at the literal, which is read-only.

  4. How do you test whether two strings hold the same characters?

    • A. a == b
    • B. a = b
    • C. strcmp(a, b) == 0
    • D. sizeof(a) == sizeof(b)
    Show answer

    Answer: C. == compares addresses, = is not allowed for arrays, and sizeof compares capacities, not contents.

  5. What is the smallest array that can hold a string of up to 11 characters?

    • A. 10 bytes
    • B. 11 bytes
    • C. 12 bytes
    • D. 13 bytes
    Show answer

    Answer: C. Eleven characters plus the terminator need 12 bytes.

  6. With scanf("%s", name), what happens if the user types Anil Reddy?

    • A. name holds both words
    • B. name holds Anil and the rest stays in the input
    • C. name holds Reddy
    • D. The program always crashes
    Show answer

    Answer: B. %s stops at whitespace. The remaining text waits in the input buffer for the next read.

  7. Which statement about "b" is true?

    • A. It is the integer 98
    • B. It is an array of two chars
    • C. It is a pointer variable
    • D. It is the same as 'b'
    Show answer

    Answer: B. The literal holds the letter and a terminator. The integer 98 is 'b'.

  8. Which function was removed from the C standard in C11 because it cannot limit input?

    • A. gets
    • B. fgets
    • C. snprintf
    • D. strlen
    Show answer

    Answer: A. gets has no size argument, so it can never be used safely.

C Strings Quiz: Predict the Output

Each snippet sits inside a main function with stdio.h and string.h included. The answers were produced by compiling and running the code with gcc.

  1. char s[] = "ABC";
    printf("%zu %zu\n", sizeof s, strlen(s));
    Show answer

    Output: 4 3

    sizeof counts the terminator, strlen does not.

  2. char s[10] = "ab";
    printf("%zu %zu\n", sizeof s, strlen(s));
    Show answer

    Output: 10 2

    The array has capacity 10, but the text is two characters long.

  3. printf("%c\n", "firmware"[3]);
    Show answer

    Output: m

    Index 3 of f-i-r-m-w-a-r-e, counting from 0, is m.

  4. printf("%zu %zu\n", sizeof("a"), sizeof('a'));
    Show answer

    Output: 2 4

    A string literal is two bytes; a character constant is an int, four bytes on typical platforms.

  5. char s[] = "ab\0cd";
    printf("%zu %zu\n", sizeof s, strlen(s));
    Show answer

    Output: 6 2

    The array holds a, b, NUL, c, d and the final NUL, but strlen stops at the first NUL.

  6. char s[] = "hello";
    s[0] = 'J';
    puts(s);
    Show answer

    Output: Jello

    The array is a writable copy, so the edit is allowed.

  7. printf("Pin" "Out" "\n");
    Show answer

    Output: PinOut

    Adjacent literals are joined by the compiler.

  8. const char *p = "hello";
    printf("%c%c\n", *p, *(p + 4));
    Show answer

    Output: ho

    The first and the fifth characters.

  9. char s[] = "cat";
    char *p = s;
    p++;
    printf("%s\n", p);
    Show answer

    Output: at

    p now points at the second character, and %s prints from there to the terminator.

  10. printf("%.3s|\n", "firmware");
    Show answer

    Output: fir|

    The precision limits the output to three bytes.

Programming Challenges

Write each one as a function with its own main test, and compile with -Wall -Wextra.

  1. Count vowels. Return how many of a, e, i, o, u appear in a string. For "firmware" the answer is 3.
  2. Reverse in place. Reverse a writable char array using two pointers that move toward each other. "UART" becomes "TRAU". Remember that a literal cannot be reversed; copy it first.
  3. Write your own compare. Implement ep_strcmp that returns zero when two strings are equal and a negative or positive value otherwise, without calling the library.

C Strings Interview Questions With Answers

1. Does C have a string type?

No. A string is a convention: a char array that ends with a zero byte. Library functions rely on that terminator.

2. What is the difference between char *p = "hi" and char a[] = "hi"?

The first creates a pointer to a read-only literal; modifying the text is undefined. The second creates a three-byte array initialised from the literal; it is your own copy and is writable. sizeof gives the pointer size for the first and 3 for the second.

3. What is the difference between sizeof and strlen?

sizeof is a compile-time capacity in bytes, including the terminator. strlen is a run-time count of characters before the first zero byte.

4. Why does if (s1 == s2) not compare strings?

It compares the two addresses. Identical text in two places has two addresses, and whether identical literals share one is unspecified. Use strcmp.

5. Explain '\0', '0' and NULL.

'\0' is the NUL character with value 0 that ends strings. '0' is the digit character, value 48. NULL is a null pointer constant for pointers.

6. What happens if you write to a string literal?

Undefined behaviour. On Linux the literal sits in read-only memory and the program receives a segmentation fault. On a microcontroller it may fault, do nothing or misbehave, depending on the part. Declare such pointers const char * to turn the mistake into a compile error.

7. Where are string literals stored on an embedded target, and how do you reduce their RAM use?

Normally in a read-only data section placed in flash, with only the pointer in RAM. On Harvard parts such as classic AVR they may be copied into RAM unless you use the toolchain’s program-memory support. Use static const char[] for fixed text and avoid local char arrays initialised from literals in hot functions, since each call copies the bytes.

8. How many bytes does char s[] = "ab\0cd" occupy, and what does strlen return?

Six bytes: a, b, NUL, c, d, and the final NUL. strlen returns 2 because it stops at the first NUL.

9. Why is gets dangerous?

It takes no size, so any line longer than the buffer overflows it. It was removed in C11. Use fgets with the buffer size.

10. What does scanf("%s", buf) stop at, and how do you make it safe?

It skips leading whitespace and stops at the next whitespace. Add a width one smaller than the array, for example %15s for a 16-byte buffer, and check the return value.

11. Why is for (i = 0; i < strlen(s); i++) slow?

strlen scans the whole string on every iteration, making the loop quadratic. Call it once before the loop or test for the terminator directly.

12. Write a length function using pointer subtraction.

Walk a second pointer to the terminator and subtract:

size_t ep_len(const char *s)
{
    const char *p = s;
    while (*p != '\0')
        p++;
    return (size_t)(p - s);
}
13. How can you print a buffer that has no terminator?

Give the conversion a precision: printf("%.4s", buf) prints at most four bytes and never looks further. This matters for raw serial buffers.

14. What does the compiler do with "Boot" " " "OK"?

It joins adjacent literals into one, "Boot OK", with a single terminator. This happens at compile time and has no run-time cost.

Best Practices, Performance and Security Recap

  • Use const char * for literals, arrays for text you edit, and capacity equal to longest text plus one.
  • Bound every read and every copy, and trust no external string to be terminated.
  • Performance: keep literals in flash, avoid repeated strlen calls, and avoid copying text you only need to read.
  • Security: overflows from unbounded input are among the most exploited bugs in C. Widths, fgets and snprintf are your tools.

Summary and Conclusion

You have finished the Strings chapter of the free C programming course. You know that C text is bytes plus a terminator, that quoted literals are read-only arrays that behave like pointers, that your own string variables need one spare byte, that loops end on the NUL, and that input functions need limits. The lab showed these ideas working together in a command matcher, and the quiz and interview questions gave you a way to check your understanding the way an interviewer would.

Next in the free embedded C course comes the standard string library: strlen, strcpy, strcmp, strcat and their safer relatives. With the memory picture from this chapter, each of those functions will feel like a short loop you could have written yourself, because it is.

Frequently Asked Questions

How should I prepare for C strings interview questions?

Know the memory picture cold: char array, terminator, pointer to a literal. Practise predicting the output of short snippets, and be ready to write strlen, strcmp and a string reverse on a whiteboard without library help.

Which C strings topics do embedded interviews ask most?

The difference between char *p = "x" and char a[] = "x", sizeof versus strlen, why literals are read-only, buffer overflow with scanf and strcpy, and where literals are stored on a microcontroller.

Are the quiz answers in this lecture tested?

Yes. Every output-prediction snippet was compiled with gcc using the C17 standard and the results shown are the real output. The answers assume a platform where int is four bytes, which is the case on desktop systems and 32-bit microcontrollers.

Why does the lab copy each input into a buffer before converting it to uppercase?

Because the inputs are string literals and literals must not be modified. The copy into a writable array is the safe pattern, and snprintf keeps the copy within the buffer.

How can I extend the command lab?

Add argument parsing: split the buffer at the first space, match the command name, and pass the remainder to a handler through an array of function pointers. That combines strings with the function pointer techniques from the Pointers chapter.

What should I study after the Strings chapter?

Move on to the standard string library (strlen, strcpy, strcmp, strncpy, strcat and friends), then to structures, where fixed-size name arrays live inside records, and then to file handling.

Topics Covered in This Lecture

C strings interview questionsC strings quizembedded C interviewcommand parser laboutput predictionfree embedded C coursefree C programming course

Keep Going With the Free C Programming Course

EmbeddedPathashala teaches C from the first printf to embedded-ready pointers and strings, completely free. Next: the standard string library functions.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

1 Comment

Leave a Reply

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