Storing Strings as Character Pointers
Strings can be stored using character pointers in two ways:
Read-only string in a shared segment.
The directly assigned string values to a pointer are stored in a read-only block shared among functions in most compilers.
char *str = "Ninja";
The word “Ninja” is stored in a shared read-only location while the pointer str is stored in read-write memory. The pointer str can be changed to point to something else, but it cannot change the value at the present str. So this kind of string should be used only when the string is not modified at a later stage in the program.
Also see, Short int in C Programming
Must Read Passing Arrays to Function in C
Dynamically allocated in the heap segment.
Strings are stored like other dynamically allocated things in C and shared among functions.
char *str;
int size = 6; /*one extra for ‘\0’*/
str = (char *)malloc(sizeof(char)*size);
*(str+0) = 'N';
*(str+1) = 'i';
*(str+2) = 'n';
*(str+3) = 'j';
*(str+4) = 'a';
*(str+5) = '\0';
Now let us see some example codes to understand the concept better.
Example 1 (modify a string)
int main()
{
char str[] = "Ninja";
*(str+1) = 'n';
getchar();
return 0;
}
Example 2 (Try to return string from a function)
char *getString()
{
char *str = "Ninja";
return str;
}
int main()
{
printf("%s", getString());
getchar();
return 0;
}
The above code works perfectly fine as the string is stored in a shared segment and data stored remains there even after return of getString().
You can also read about the dynamic arrays in c, and Tribonacci Series
Must Read what is storage class in c and Decision Making in C
Frequently Asked Questions
How is a string stored in C?
The strings declared as character arrays are stored like other arrays in C. For example, if str[] is an auto variable, the string is stored in the stack segment; if it’s a global or static variable, then stored in the data segment.
Where is a string stored in memory in C?
Representing a string in C: A string is stored in memory using consecutive memory cells and the string is terminated by the sentinel '\0' (known as the NULL character).
Conclusion
In this article, we have discussed how strings are stored in memory in the C language. Having gone through this article, I am sure you must be excited to read similar blogs. Coding Ninjas has got you covered. Here are some similar blogs to redirect: Understanding strings in C, Reverse A String In C, Storage Class and Introduction to strings. We hope that this blog has helped you enhance your knowledge, and if you wish to learn more, check out our Coding Ninjas Blog site and visit our Library. Here are some courses provided by Coding Ninjas: Basics of C++ with DSA, Competitive Programming and MERN Stack Web Development. Do upvote our blog to help other ninjas grow.
Happy Learning!