Concept
How can you create static strings with character arrays?
ComputerScienceOne / Character Arrays
"We’ve previously used string literals when using the standard input and output functions, printf() and scanf(). You can also create static strings (as static arrays) using the standard assignment operator. Some examples:\n\nchar firstName[] = \"Tom\";\n\nchar lastName[] = \"Waits\";\n\nA string in C is achieved by using a char array. However, the string is terminated by a null-terminating character, \\0. Though an array may have space for additional characters, they are irrelevant if the null terminator precedes them.\n\nThis syntax can only be used when creating static strings (they are allocated on the stack and locally scoped). The compiler is able to scan the string literal and determine how many characters are needed and even inserts the null-terminating character for us. Thus, the length of the two strings in the example are 3 and 5 respectively, but the array size created for them will be 4 and 6 respectively to accommodate the null-terminating character. Static strings have the same limitations as static arrays. Since they are allocated on the stack, they cannot be returned from a function."
Related Ideas
- How can you create an array of strings in C?ComputerScienceOne · Arrays of Strings
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How can strlen determine the length of a C string?ComputerScienceOne · String Library
- How can you convert a Student structure into a string?ComputerScienceOne · To String Functions
- How do you access array elements safely in C?ComputerScienceOne · Basic Usage
- How can strings be created and assigned to variables?ComputerScienceOne · Basic Operations
- Why can’t numerical comparison operators be used to compare strings in C?ComputerScienceOne · Comparisons
- What sections cover static-array pitfalls and application memory?ComputerScienceOne · Example returning a static array