What are Array vs Pointer Strings- 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 →

Array

Array vs Pointer Strings

Chapter 9, Strings: understand the real difference between char name[] and char *name, where each one lives in memory, and what you may safely do with them. Free embedded C course by EmbeddedPathashala.

The question of C string array vs pointer confuses almost every beginner, because both forms accept the same quoted text and both work with printf. In this lecture of our free C programming course you will learn what each declaration really creates in memory, which operations are legal on each, and why the answer matters for RAM and flash usage in embedded C programming.

Topics in This Lecture

C string array vs pointer string literal const char pointer free C programming course c programming for embedded systems free C tutorial

What You Will Learn

  • What char name[] = "text" creates, and what const char *name = "text" creates.
  • Where the bytes live: writable data, read-only data or flash.
  • Which assignments and modifications are legal for each form.
  • How sizeof behaves differently for arrays and pointers.
  • How to choose the right form to save RAM on a microcontroller.

Prerequisites

You should know that a string is a zero-terminated sequence of characters, understand pointer variables and addresses, and have seen how an array name behaves as the address of its first element. The earlier copy and concatenation lectures in this chapter are useful background.

Two Declarations, Two Different Objects

Look at these two lines:

char arr[] = "mode_a";          /* an array of 7 chars */
const char *ptr = "mode_b";     /* a pointer to a string literal */

The first line creates an array of seven char elements, six letters plus the terminator, and fills it with a copy of the text. The array is your own variable. You can change its elements freely. The second line creates a single pointer variable. The text itself is a separate string literal that the compiler stores elsewhere, and the pointer simply holds its address. You do not own those bytes, and you promise not to modify them, which is why the pointer is declared const char *.

Memory View: char arr[] = “mode_a”

Elementarr[0]arr[1]arr[2]arr[3]arr[4]arr[5]arr[6]
Valuemode_a\0

Memory View: const char *ptr = “mode_b”

ObjectHoldsWhere it lives
ptr (the variable)Address of the first letter mRAM, stack or static data
“mode_b” (the literal)m o d e _ b \0 (seven bytes)Read-only data, often flash on a microcontroller

Complete Program: Seeing the Difference

This original program prints sizes and lengths, then performs the one change that is legal for each form. Save it as ep_arrptr.c:

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

int main(void)
{
    char arr[] = "mode_a";
    const char *ptr = "mode_b";

    printf("sizeof arr = %zu\n", sizeof arr);
    printf("sizeof ptr = %zu\n", sizeof ptr);
    printf("strlen arr = %zu\n", strlen(arr));
    printf("strlen ptr = %zu\n", strlen(ptr));

    arr[5] = 'z';                 /* legal: change one element */
    ptr = "mode_c_longer";        /* legal: point somewhere else */

    printf("arr now : %s\n", arr);
    printf("ptr now : %s\n", ptr);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_arrptr ep_arrptr.c
$ ./ep_arrptr
sizeof arr = 7
sizeof ptr = 8
strlen arr = 6
strlen ptr = 6
arr now : mode_z
ptr now : mode_c_longer

The output above comes from a 64-bit computer, where a pointer occupies eight bytes. On a 32-bit microcontroller such as a Cortex-M device the pointer size is four, so you would see 4 on the second line. The first line is always 7, because sizeof applied to an array counts every element including the terminator, while strlen stops before the terminator.

C String Array vs Pointer: Comparison Table

Propertychar arr[] = “text”const char *p = “text”
What the variable isThe whole block of charactersOne address
sizeof resultCharacters plus terminatorSize of a pointer
Change an elementAllowedNot allowed, undefined behaviour
Assign a new string to the nameCompile error, array names are not assignableAllowed, pointer now refers to another literal
Where the characters liveYour writable storageRead-only literal storage
RAM costFull length of the textOnly the pointer
Extra copy made at startupYes, text is copied inNo copy

A line such as arr = "other"; is rejected by the compiler because arr names a fixed block, not a variable that holds an address. To change an array’s contents you must copy characters into it, for example with the copy function from earlier lectures.

Why Embedded Programmers Care

On a microcontroller RAM is scarce and flash is plentiful. When you write char banner[] = "firmware v2"; as a global or static variable, the text must exist in flash and also in RAM, because the startup code copies the initial value across before main runs. When you write const char *banner = "firmware v2";, only the address occupies RAM and the characters stay in flash. For a table of fifty messages this difference can be the deciding factor in whether the program fits.

If the text is a constant, make that explicit and let the toolchain place it in read-only memory:

static const char banner[] = "firmware v2";     /* whole string in flash */
static const char *const level_name = "warning"; /* pointer and text both fixed */

The first line keeps the array itself constant, so no RAM copy is needed. The second line makes even the pointer constant, which also lets the linker place it in flash.

Real-World Use Cases

  • Use a writable array for a name the user can edit, such as a device label received over a configuration interface.
  • Use a pointer to a literal for fixed menu text, error messages and protocol keywords.
  • Use a constant array for lookup text that must not use RAM at all.
  • Switch between literals at run time by changing a pointer, for example to select a language or a log level name.

Common Mistakes and Troubleshooting

Warning: writing into a string literal through a pointer compiles on many systems but fails at run time. On a desktop it is usually a segmentation fault, and on some microcontrollers it silently does nothing or triggers a hard fault.

  • Modifying a literal. char *p = "abc"; p[0] = 'X'; is undefined behaviour. Use const char * so the compiler catches it.
  • Assuming sizeof gives the string length. It gives the array size, and for a pointer it gives the pointer size. Use strlen for the text length.
  • Passing an array and using sizeof inside the function. The array decays to a pointer, so sizeof then reports the pointer size.
  • Comparing strings with ==. Two pointers compare equal only if they hold the same address. Use strcmp to compare the text.
  • Making an array too small. char s[5] = "fault"; is accepted by C but leaves no room for the terminator, so the result is not a string.

Best Practices, Performance and Security

  • Declare pointers to literals as const char *, always.
  • Use arrays when you need to modify text, and give them room for the terminator.
  • Let the compiler size an array by writing empty brackets with an initialiser, which avoids off-by-one mistakes.
  • Prefer constant data for fixed messages so that it stays in flash.
  • Remember that two identical literals may or may not share storage, so never rely on their addresses.
  • Treat modification of read-only data as a security defect as well as a crash risk, because it is a sign of confused ownership of memory.

Summary and Key Takeaways

  • An array initialised with a string owns its characters, and you can change them.
  • A pointer initialised with a string only holds an address of read-only text.
  • Array names cannot be reassigned, but pointer variables can.
  • sizeof on an array includes the terminator, and sizeof on a pointer is the pointer size.
  • Pointers to literals save RAM, which is valuable in embedded designs.

Conclusion

The C string array vs pointer choice is really a choice about ownership and storage. Arrays give you a private, writable copy at the price of RAM. Pointers to literals are cheap and fast to repoint, but they are strictly read-only. Once you see strings this way, many puzzling crashes and size calculations become easy to explain. The next lecture takes the pointer side further and shows how to use pointer strings safely, including how to give them real, writable memory.

Frequently Asked Questions

What is the difference between char s[] and char *s for strings in C?

char s[] creates a writable array that holds a copy of the text. char *s creates a pointer to a string literal that you must treat as read-only.

Can I change a character through a char pointer to a literal?

No. It is undefined behaviour and often crashes, because literals can be stored in read-only memory.

Why does sizeof give different results for an array and a pointer?

For an array it returns the total bytes of the array, including the terminator. For a pointer it returns the size of the address, such as 4 or 8 bytes.

Which form uses less RAM on a microcontroller?

A pointer to a constant literal uses only the pointer’s RAM, while a writable array also needs RAM for every character. A constant array can stay in flash.

Why can I assign a new string to a pointer but not to an array name?

A pointer is a variable that holds an address and can hold another one. An array name refers to a fixed block of storage and is not assignable.

Learn C the Free Way

Compile the example on your computer, then change one line at a time and watch the compiler react. This free embedded C course is designed for exactly that kind of hands-on practice.

💬 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 →