🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Assigning Strings to Arrays
Free C tutorial: why names[0] = "UART" fails, and the safe ways to copy text into the rows of a string array.
Beginners often try to fill an array of strings with simple assignment and meet a compiler error. This lecture of our free C programming course explains exactly why assigning strings to arrays with = is rejected, then shows the correct tools: strcpy, strncpy, snprintf, memcpy and fgets. These are the same calls you will use in real embedded C programming when a UART receives a name or a command at run time.
What You Will Learn
- Why an array name cannot appear on the left of an assignment
- The exact compiler error you will see and what it means
- How to copy a string into a row with bounded functions
- Why
strncpyneeds extra care with the terminator - How
snprintftruncates safely - How to read a line from input into a row and strip the newline
Prerequisites
You need the previous two lectures on the two-dimensional string table and its padding, plus basic knowledge of <string.h> and printf. Compile everything with gcc -std=c17 -Wall -Wextra.
Why You Cannot Assign a String to an Array Row
Look at this fragment:
char names[3][8];
names[0] = "UART";
GCC rejects it:
error: assignment to expression with array type
Older compilers phrase the same problem as an lvalue error. The reason is the same: names[0] is an array of eight characters, and C does not let you assign a whole array. Arrays are not modifiable objects as a unit. You can change an element of an array, but you cannot replace the array itself with one statement. The string literal on the right is also an array, a read-only one, and C has no rule that copies one array into another through =.
| Statement | Legal? | Reason |
|---|---|---|
char a[8] = "UART"; | Yes | This is initialization, not assignment |
names[0] = "UART"; | No | Assignment to an array |
names[0] = names[1]; | No | Both sides are arrays |
names[0][0] = 'U'; | Yes | A single char element is modifiable |
strcpy(names[0], "UART"); | Yes | A function copies the bytes |
Copying Strings the Right Way
strcpy: simple but unbounded
strcpy(dest, src) copies characters up to and including the NUL. It does not know how big dest is, so a long source silently overflows. It is acceptable only when you can prove the source fits, for example when copying a literal that you checked with _Static_assert.
strncpy: bounded but easy to misuse
strncpy(dest, src, n) copies at most n bytes. If src is shorter, it pads the rest with zeros. If src has n or more characters, it copies exactly n bytes and does not add a NUL. The fix is to copy one byte fewer and terminate yourself:
strncpy(names[0], "UART", LEN - 1);
names[0][LEN - 1] = '\0';
snprintf: bounded and always terminated
snprintf(dest, size, format, ...) writes at most size - 1 characters and always adds the NUL, as long as size is at least 1. It also lets you build text from numbers, such as "SPI%d".
memcpy: copying a whole row
To move one complete row into another, copy the full row width with memcpy, using the same size as the row. This is what a swap needs, and we use it in the sorting lecture.
A Complete Example
Save this as assign.c:
#include <stdio.h>
#include <string.h>
#define COUNT 3
#define LEN 8
int main(void)
{
char names[COUNT][LEN];
strncpy(names[0], "UART", LEN - 1);
names[0][LEN - 1] = '\0';
snprintf(names[1], sizeof names[1], "%s", "TIMER2_LONG");
snprintf(names[2], sizeof names[2], "SPI%d", 2);
for (int i = 0; i < COUNT; i++)
printf("names[%d] = \"%s\" (len %zu)\n", i, names[i], strlen(names[i]));
memcpy(names[0], names[2], LEN);
printf("after copy names[0] = %s\n", names[0]);
return 0;
}
gcc -std=c17 -Wall -Wextra -o assign assign.c
./assign
GCC warns that the output of %s may be truncated at the TIMER2_LONG line. That is a helpful warning, because we truncate on purpose to show the behavior. The program output is:
names[0] = "UART" (len 4)
names[1] = "TIMER2_" (len 7)
names[2] = "SPI2" (len 4)
after copy names[0] = SPI2
Row 1 holds only seven characters because the eighth byte is the NUL. Row 2 shows snprintf building text from a number. The final line proves that memcpy over the full row width replaced the old contents, including the leftover bytes after the terminator.
Detecting truncation
Silent truncation can hide a bug. snprintf returns the number of characters it would have written if the buffer were unlimited, which gives you a cheap way to detect a cut:
#include <stdio.h>
int main(void)
{
char buf[8];
int n = snprintf(buf, sizeof buf, "%s", "TIMER2_LONG");
printf("needed %d characters, stored [%s]\n", n, buf);
if (n >= (int)sizeof buf)
printf("truncated\n");
return 0;
}
needed 11 characters, stored [TIMER2_]
truncated
The return value 11 is larger than the 7 characters that fit, so the program knows the text was cut. In firmware you might log a warning, raise an error code, or switch to a larger row. The important point is that you chose what happens, instead of discovering a corrupted neighbor row later.
Reading Input into a Row
Real programs receive text instead of literals. fgets reads a line with a size limit, but it keeps the newline if there is room. Remove it with strcspn:
#include <stdio.h>
#include <string.h>
#define LEN 16
int main(void)
{
char cmd[LEN];
printf("enter command: ");
if (fgets(cmd, sizeof cmd, stdin) == NULL)
return 1;
cmd[strcspn(cmd, "\n")] = '\0';
printf("stored: [%s] length %zu\n", cmd, strlen(cmd));
return 0;
}
$ echo "reset" | ./readcmd
enter command: stored: [reset] length 5
If the typed line is longer than 15 characters, fgets stops after 15 and leaves the rest unread. With input start_motor_now_long the stored value is start_motor_now, length 15. You decide whether that truncation is acceptable. The same idea applies to scanf("%7s", names[i]): always give a width that is one less than the row size.
A firmware scenario
Imagine a device that stores up to four user-defined sensor labels, each at most 11 characters, and receives new labels over UART. Each label is a row of char labels[4][12]. When a label arrives, the handler validates the slot index, copies the text with snprintf into labels[slot], and checks the return value against sizeof labels[slot]. If the text was too long, it replies with an error instead of storing a clipped label. This small discipline, validate the index, bound the copy, check for truncation, prevents most string bugs in embedded C programming.
Which Copy Function Should You Use?
| Function | Bounded? | Always adds NUL? | Best for |
|---|---|---|---|
strcpy | No | Yes | Literals proven to fit |
strncpy | Yes | No | Fixed-width fields, with manual NUL |
snprintf | Yes | Yes | Formatted or truncating copies |
memcpy | By your size | No, copies raw bytes | Whole-row copy or swap |
fgets | Yes | Yes | Reading a line from a stream |
strcpy with text from outside the program; forgetting that strncpy may leave no terminator; passing sizeof(char *) instead of the row size; and leaving the trailing newline from fgets inside the string so that later strcmp calls never match.
Best Practices for Assigning Strings to Arrays
- Prefer
snprintfwithsizeof destinationfor run-time text. - Always use the row size from
sizeof, never a typed number that can drift. - Check input length when a silent cut would change the meaning of a command.
- Treat compiler truncation warnings as design feedback, not noise.
Security and performance notes
Unbounded copies are the classic source of buffer overflow bugs, and in firmware a stray write can corrupt a neighboring row or a variable beside the table. Bounded calls cost almost nothing extra, so there is no reason to skip them. Choose the cheapest function that is still safe for the data source.
Summary and Key Takeaways
- You cannot assign to an array, so
names[i] = "text"is an error. - Initialization at declaration is allowed because the compiler fills the array.
- Use
snprintf, boundedstrncpywith manual NUL, ormemcpyto copy. fgetsreads a line safely; strip the newline withstrcspn.- Always bound copies by the row size.
Conclusion
You can now fill an array of strings from literals, formatted values and input without breaking the array rules. The next lecture uses strcmp and a whole-row copy to sort a table of names, a very common task in embedded C programming and in interviews.
Frequently Asked Questions
Why is names[0] = “UART” an error?
Because names[0] is an array, and C does not allow an array to be the target of an assignment.
How do I assign a string to a char array in C?
Initialize it at declaration, or copy at run time with strcpy, strncpy, snprintf or memcpy.
Is strncpy safe?
It is bounded, but it does not add a NUL when the source fills the limit, so you must terminate manually.
Why use snprintf instead of strcpy?
It never writes past the size you give it and always terminates the result.
Why does my strcmp fail after fgets?
The newline that fgets keeps is part of the string. Remove it before comparing.
Can I copy one row into another row?
Yes, with memcpy using the full row width, or with strcpy if the source string is shorter than the destination row.
Free Embedded C Course, Next Step
Continue this free C tutorial with sorting an array of strings using strcmp.

2 Comments