Memory Representation Using Char Arrays
Get introduced to strings in C from a memory point of view.
Introduction
In C, we represent strings using char
arrays. Therefore, everything we discussed in the “Pointers And Arrays” chapter holds for this chapter.
However, a few things are specific to character arrays, which we’ll now discuss.
In this chapter, we’ll refer to character arrays as strings.
First code with char arrays
Let’s use the ARRAY_SIZE
macro with a character array and see if we can deduce its number of elements.
Moreover, let’s also print the string’s size in bytes.
#include <stdio.h>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))int main(){char str[32];printf("sizeof(str) = %u\n", sizeof(str));printf("ARRAY_SIZE(str) = %u\n", ARRAY_SIZE(str));return 0;}
The output is as follows:
sizeof(str) = 32
ARRAY_SIZE(str) = 32
sizeof
: The size of the array is 32 bytes. The string has 32 elements, and each element is achar
that occupies 1 byte. 1 * 32 = 32 bytes.ARRAY_SIZE
: The number of elements in the array is 32 since each is 1 byte.
Previously, we noticed a difference between the total size and number of elements for integer arrays. It happened because the size of int
was 4 bytes. The size of char
is 1 byte, so the total size and the number of elements are equal.
In conclusion, sizeof
and ARRAY_SIZE
are equivalent for character arrays. In this chapter, we’ll use sizeof
to determine the number of elements in a char
array. We stress again that for all other data types, we have to use ARRAY_SIZE
.
Memory drawing
Let’s assume the following string declaration: ...