String In C
In c, there is no string, but an array of characters.
For example, a string can be declared as follows:
char my_string[40];
my_string[0] = 'T';
my_string[1] = 'e';
my_string[2] = 'd':
my_string[3] = '\0';
or
char my_string[40] = {'T', 'e', 'd', '\0',};
[!note]
By definition, a string is an array of character and terminate bynulcharacter\0Note: this is different thanNULL
We can also declare a string with double quote which c will automatically add a nul for us in the end:
char my_string[40] = "Ted";
// or
char my_string[] = "Ted";
[!danger]
When declaring a string, if we declare like this without having a pointer for it:char myString[] = "ABC".myStringwill be stored in the Stack ."ABC"is a string literals, this is typically stored in Data segment. In this situation, when we returnmy_stringfrom a function, its value will be lost after terminate from the stack. This is because themy_stringsimply is arvalueof"ABC"which refers to the actual value (not pointer).However if you declare like this:
char *myString = "DEF".myStringwill be stored Stack."DEF"is initialised value and will be stored in Data segment. However,myStringwill take the memory address of"DEF". Therefore, when returningmyStringfrom a function, you essentially just return the memory address of"DEF"and won't lose the value#include <stdio.h> char *getString(void) { /*char *myString = "hell";*/ char *myString = "hell"; return myString; } int main(void) { printf("Result of myString is: %s\n", getString()); }