🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Array Parameters and String Quiz
Array parameters, case-insensitive compare, a C strings quiz and embedded C strings interview questions.
This closing lecture of the strings chapter does three jobs. It explains what really happens when you pass a character array to a function, it walks you through a practical lab where you write your own case-insensitive string comparison, and it finishes with a quiz and a set of c strings interview questions that embedded companies love to ask. Everything is part of our free C programming course, written for students who want solid C programming for embedded systems.
What You Will Learn
- Why
char x[]in a parameter list is really a pointer, and what that means forsizeof - The difference between reassigning a parameter and editing the caller’s data
- How to implement a case-insensitive string comparison correctly, including the
unsigned charcast - How to test your function against the POSIX
strcasecmp - How to check yourself with a ten question C strings quiz
- Twelve C strings interview questions with short model answers
Prerequisites
You should have worked through the earlier lectures on string pointers, literals, appending, wild and dangling pointers, and parsing. This is the closing lecture of the strings chapter in our free C tutorial, so every idea below builds on those. Programs were compiled with GCC 13, -std=c11 -Wall -Wextra, on 64-bit Linux, which matters for the pointer size shown in one output.
Array Parameters in C Strings Behave Like Pointers
When you write a function such as void f(char x[]), the compiler quietly treats the parameter as char *x. Arrays are never copied into functions; only the address of the first element travels. Three consequences follow, and the first lab program demonstrates all of them.
sizeof xinside the function is the size of a pointer, not the size of the array.- Assigning to
xonly changes the function’s local copy of the address. The caller’s array is unaffected. - Writing through
x[i]changes the caller’s real data, because both refer to the same bytes.
#include <stdio.h>
static void rebind(char *x)
{
x = "REBOUND";
printf("inside rebind: %s\n", x);
}
static void edit(char *x)
{
x[0] = 'L';
x[1] = 'E';
x[2] = 'D';
x[3] = '\0';
printf("inside edit : %s\n", x);
}
static void size_inside(char x[])
{
printf("sizeof inside function: %zu\n", sizeof x);
}
int main(void)
{
char tag[16] = "init";
printf("sizeof in main : %zu\n", sizeof tag);
size_inside(tag);
rebind(tag);
printf("after rebind : %s\n", tag);
edit(tag);
printf("after edit : %s\n", tag);
return 0;
}
GCC even warns about the sizeof line, which is a helpful sign that you are about to make a classic mistake:
p47a.c:20:52: warning: 'sizeof' on array function parameter 'x' will return size of 'char *' [-Wsizeof-array-argument]
Running the program prints:
sizeof in main : 16
sizeof inside function: 8
inside rebind: REBOUND
after rebind : init
inside edit : LED
after edit : LED
Study the contrast between the last four lines. After rebind the caller still sees init, because only the local pointer was redirected to a literal. After edit the caller sees LED, because the characters themselves were overwritten. If you actually want a function to replace a pointer in the caller, you must pass the address of the pointer, which means a pointer-to-pointer parameter.
Parameter x inside rebind versus the caller array
Warning: never print or process an array that has not been initialised. An uninitialised char arr[5] contains whatever was in memory, so puts(arr) has no defined result and may run far past five bytes before it finds a zero.
Case-Insensitive Compare Lab
Command interpreters often need to treat START, Start and start as the same word. The POSIX function strcasecmp does that, but it is not part of standard C, and some small embedded libraries leave it out. Writing your own is a perfect exercise for string traversal.
Design of the Function
- Walk both strings in step while neither has reached its NUL.
- Convert each character to lower case with
tolowerand compare. - On the first difference, return the numeric difference; its sign says which string sorts first.
- When the loop ends, compare the last two characters, so that a shorter string sorts before a longer string with the same start.
One subtle point deserves emphasis. The ctype.h functions require an argument that is representable as unsigned char (or equal to EOF). Passing a plain char that holds a negative value, as happens with accented characters on many platforms, is undefined behaviour. That is why the code casts each character to unsigned char first.
#include <ctype.h>
#include <stdio.h>
#include <strings.h>
static int ep_strcasecmp(const char *a, const char *b)
{
while (*a != '\0' && *b != '\0') {
int ca = tolower((unsigned char)*a);
int cb = tolower((unsigned char)*b);
if (ca != cb)
return ca - cb;
a++;
b++;
}
return tolower((unsigned char)*a) - tolower((unsigned char)*b);
}
static int sign(int v)
{
return (v > 0) - (v < 0);
}
int main(void)
{
const char *pairs[][2] = {
{"START", "start"},
{"On", "oN"},
{"abc", "ABD"},
{"Zeta", "alpha"},
{"mode", "mode2"},
{"", ""},
};
size_t i;
for (i = 0; i < sizeof pairs / sizeof pairs[0]; i++) {
const char *a = pairs[i][0], *b = pairs[i][1];
printf("\"%s\" vs \"%s\" -> mine=%2d posix=%2d\n", a, b,
sign(ep_strcasecmp(a, b)), sign(strcasecmp(a, b)));
}
return 0;
}
Build and run on Linux:
gcc -std=c11 -Wall -Wextra -o p47b p47b.c
./p47b
"START" vs "start" -> mine= 0 posix= 0
"On" vs "oN" -> mine= 0 posix= 0
"abc" vs "ABD" -> mine=-1 posix=-1
"Zeta" vs "alpha" -> mine= 1 posix= 1
"mode" vs "mode2" -> mine=-1 posix=-1
"" vs "" -> mine= 0 posix= 0
The helper sign exists because the standard only promises a negative, zero or positive value, not exactly minus one or plus one. Normalising both results makes the comparison between your function and the library fair. All six rows match, including the interesting cases: the equal strings with different capitals, the pair that differs only at the last letter, and the empty pair.
Walk of ep_strcasecmp for abc and ABD
Extending the Lab
- Add a length limit parameter to build an
ep_strncasecmp, stopping after n characters. - Use the function to look up a command name in a table of keywords and return its index.
- Test the empty string, a one character string and strings with digits and punctuation.
Common Mistakes With Array Parameters and Comparison
| Mistake | Result | Fix |
|---|---|---|
Using sizeof on an array parameter | Pointer size, not array size | Pass the length as a separate argument |
| Assigning a new literal to the parameter to “change the string” | Caller does not see the change | Write into the array, or pass a pointer to the pointer |
Calling tolower on a plain char | Undefined for negative values | Cast to unsigned char |
Comparing results with == -1 or == 1 | Breaks on implementations returning other values | Test the sign: less than, equal, greater than zero |
Comparing strings with == | Compares addresses | Use strcmp or your own compare function |
Best Practices, Performance and Security
- Pass buffer sizes alongside pointers; the compiler cannot recover them.
- Mark input parameters
const char *and output buffers plainchar *so intent is visible. - Remember that
tolowerdepends on the current locale; embedded builds usually use the “C” locale, which means ASCII. - For constant-time comparison of secrets such as keys, do not use an early-exit compare, because timing leaks information.
Performance: the loop above is linear and touches each character once, which is optimal. Security: case-insensitive matching of user names or paths can create ambiguity. Decide on one canonical form for identifiers and convert once at the boundary.
C Strings Quiz Before the Interview Questions
Try each question on paper first, then click to reveal the answer. All answers were verified by compiling and running the code on GCC 13.
What does this print?
char s[] = "bootloader"; printf("%s", s + 4);Show answer
loader. The pointer s + 4 starts at the fifth character, and the text runs to the NUL.
What does this print?
printf("%zu %zu", strlen("rtos"), sizeof("rtos"));Show answer
4 5. strlen stops before the NUL, sizeof counts the whole array including it.
What happens with this code?
char a[] = "gpio"; a = a + 1;Show answer
Compile error: assignment to expression with array type. An array name cannot be reassigned.
How many elements does this array have?
const char *t[] = {"on" "off", "idle"};Show answer
2. The first two literals are joined at compile time into “onoff”, so there is no separate “on” and “off”.
Is this safe?
char buf[6] = "ab"; strcat(buf, "cdef");Show answer
No. The result needs six characters plus the NUL, seven bytes, but the array holds six. That is a buffer overflow and undefined behaviour.
What does this print?
char s[] = "A1B2C3"; char *p = s + 1; p += 2; printf("%c%s", *p, p);Show answer
22C3. After the moves p points at index 3, the character 2, so *p prints 2 and %s prints 2C3.
What is wrong with a function that builds a message in a local char array and returns the array’s name?
Show answer
It returns a dangling pointer. The local array disappears when the function returns. Use a caller buffer, a static buffer or heap memory.
What does this print?
printf("%c", "firmware"[4]);Show answer
w. Index 4 of f-i-r-m-w-a-r-e is w.
A function declared as void f(char s[]) is called with a 32 byte array. What does sizeof s print inside it?
Show answer
The size of a pointer: 8 on a typical 64-bit PC and usually 4 on a 32-bit microcontroller. It is never 32.
What does this print?
char t[] = {'O', 'K', 0, '!'}; printf("%s %zu", t, sizeof t);Show answer
OK 4. The third element is a zero byte, so %s stops there, but the array still has four elements.
C Strings Interview Questions for Embedded Roles
These c strings interview questions keep appearing in embedded C programming interviews. Try to answer aloud before you open each one.
What is the difference between char s[] = “text” and char *s = “text”?
The first creates a modifiable array in RAM initialised from the literal. The second creates a pointer to a literal in read-only storage, so writing through it is undefined behaviour. The array name cannot be reassigned; the pointer can.
Why does modifying a string literal crash?
Literals normally live in read-only memory, such as .rodata or flash. A write violates that protection and causes a fault. Declare such pointers as const char * so the compiler prevents the write.
What is the difference between strlen and sizeof on a string?
strlen counts characters up to the NUL at run time. sizeof is a compile-time size of the object, including the NUL for an array, and is just the pointer size when applied to a pointer.
What happens when you pass an array to a function?
It decays to a pointer to its first element. Nothing is copied, sizeof inside the function gives the pointer size, and writes through the parameter modify the caller’s array. The length must be passed separately.
Why is returning a local array from a function a bug?
The array has automatic storage and ends its lifetime on return, leaving the caller a dangling pointer. Safer options are a caller-supplied buffer with a size, a static buffer (not re-entrant) or heap memory (caller must free).
How would you append to a string safely?
Compute the current length, check that length plus new length plus one fits the destination capacity, then copy with memcpy or use snprintf. Always pass the capacity into the helper, never rely on sizeof of a pointer.
Why is strncpy not a safe replacement for strcpy?
If the source is as long as or longer than the limit, strncpy does not add a terminating NUL, and it pads short results with zeros, which wastes time. You must terminate manually, or use snprintf or a bounded helper.
How do you compare strings ignoring case, and why cast to unsigned char?
Convert each character with tolower and compare until a difference or a NUL. The ctype functions require values representable as unsigned char, so a negative plain char would cause undefined behaviour without the cast.
What is a format string vulnerability?
Calling printf with attacker-controlled text as the format lets conversion specifiers read or write memory. The cure is a fixed literal format: printf(“%s”, text), or puts for plain output.
What bug can adjacent string literals cause?
They are concatenated at compile time, so a missing comma in an array of strings silently merges two entries and shortens the array. Put each element on its own line and keep a trailing comma.
Why prefer strtol over atoi?
strtol reports where parsing stopped and signals overflow through errno, so invalid or partial input can be detected. atoi gives no error information.
Why does const matter for strings in embedded systems?
It lets the linker place constant text in flash instead of RAM, saving scarce memory, and it makes the compiler reject accidental writes that would otherwise fault on the device.
Summary: C Strings Interview Questions Checklist
- Array parameters are pointers;
sizeofinside a function cannot recover the array size. - Assigning to a parameter does not affect the caller; writing through it does.
- A correct case-insensitive compare casts to
unsigned charand tests only the sign of the result. - A quiz that you can answer without compiling shows you truly understand pointers and literals.
- Most c strings interview questions return to the same few ideas: ownership, lifetime, size, and safety.
Conclusion
You have now reached the end, with the main c strings interview questions behind you, of this stretch of the strings chapter. You can offset strings, understand literals, append without overflow, avoid wild and dangling pointers, parse real input and compare text correctly, and you have tested yourself against the questions interviewers actually ask. The best next step is to type every program into your own editor, break it on purpose and watch the compiler or the debugger tell you why. That habit is what turns a free C programming course into employable skill, and it is the same habit that serves anyone moving from this free embedded C course toward firmware work on real microcontrollers. When you are ready, continue with the next chapter of the series.
Frequently Asked Questions
What are the most common c strings interview questions?
Interviewers usually ask about the difference between a char array and a char pointer to a literal, strlen versus sizeof, why literals cannot be modified, safe appending and copying, returning local arrays, and how arrays behave as function parameters.
Why does sizeof give 8 for an array parameter?
An array parameter is really a pointer, so sizeof returns the pointer size, which is 8 bytes on a typical 64-bit system. Pass the array length as an extra argument instead.
Is strcasecmp part of standard C?
No. It is a POSIX function declared in strings.h. Standard C only provides strcmp, so portable embedded code often includes its own case-insensitive compare.
Why cast to unsigned char before calling tolower?
The ctype functions require an argument that fits in unsigned char or equals EOF. A plain char may be negative for non-ASCII bytes, and passing it directly is undefined behaviour.
Can a function change which string the caller points to?
Only if you pass the address of the caller’s pointer, which means a pointer-to-pointer parameter. Assigning to an ordinary pointer parameter changes only the local copy.
How do I practise for embedded C interviews?
Write small programs for each concept, compile with warnings and sanitizers enabled, and explain every output aloud. Reimplement strlen, strcpy, strcmp and a case-insensitive compare from memory.
Is this lecture part of a free embedded C course?
Yes. It is part of the free C programming course at EmbeddedPathashala, aimed at students learning embedded C programming, with tested examples in every lecture.
Keep Going With the Free C Course
EmbeddedPathashala is a free C programming course and free embedded C course built for students. Practice every example on your own machine, then move on to the next lecture.

2 Comments