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 bynul
character\0
Note: 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"
.myString
will be stored in the Stack ."ABC"
is a string literals, this is typically stored in Data segment. In this situation, when we returnmy_string
from a function, its value will be lost after terminate from the stack. This is because themy_string
simply is arvalue
of"ABC"
which refers to the actual value (not pointer).However if you declare like this:
char *myString = "DEF"
.myString
will be stored Stack."DEF"
is initialised value and will be stored in Data segment. However,myString
will take the memory address of"DEF"
. Therefore, when returningmyString
from 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()); }