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.
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 acharthat 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 ...