I’m new to C world (coming from PHP). I’m playing with strings (I know that there is no such type of data).
My question is about which is the best way to “declare” strings ?
With some research I came to that.
char str[40] = "Here is my text";
char str[] = "Here is my text";
char *str = "Here is my text";
It depends on what your needs are.
This will allocate an array of 40 characters. First 15 characters will be set according to the specified string. The rest will be set to nulls. This is useful if you need to modify the string later on, but know that it will not exceed 40 characters (or 39 characters followed by a null terminator, depending on context).
This is identical to the example above, except that
stris now limited to holding 16 characters (15 for the string + a null terminator).stris now a pointer to a string of 15 characters (plus a null terminator). You cannot modify the string itself, but you can makestrpoint somewhere else. In some environments this is not enforced and you can actually modify the string contents, but it’s not a good idea.If you do need to use a pointer and modify the string itself, you can copy it:
But you need to
free(str)or your code will leak memory.