Best way to "declare" strings in C

I am new to C world (from PHP). I play with strings (I know there is no such type of data).

My question is, what is the best way to β€œdeclare” strings?

With some research, I came to this.

char str[40] = "Here is my text"; char str[] = "Here is my text"; char *str = "Here is my text"; 
+6
source share
3 answers

It depends on your needs.

 char str[40] = "Here is my text"; 

This will contain an array of 40 characters. The first 15 characters will be set according to the specified string. The rest will be set to null. This is useful if you need to change the string later, but be aware that it will not exceed 40 characters (or 39 characters followed by a null terminator, depending on context).

 char str[] = "Here is my text"; 

This is similar to the above example, except that str now limited to storing 16 characters (15 for a string + null terminator).

 char *str = "Here is my text"; 

str now a pointer to a string of 15 characters (plus a null delimiter). You yourself cannot change the string, but you can make str dot somewhere else. In some environments, this does not apply, and you can actually change the contents of the string, but this is not a good idea. If you need to use a pointer and change the line, you can copy it:

 char *str = strdup("Here is my text"); 

But you need free(str) or your code will be a memory leak.

+8
source
 char str[40] = "Here is my text"; char str[] = "Here is my text"; 

str is modifiable. Thus,

 str[0] = 'M'; 

But,

 char *str = "Here is my text"; str[0] = 'M'; // Not possible. 

str indicating data is on a read-only segment and does not change. It all depends on what you want, whether the string should be modifiable or not.

+4
source

All this is almost the same, except that in the first case exactly 40 bytes will be reserved, whether there is too much or too little for a given string, so this is probably not the best option outside of other considerations.

-2
source

Source: https://habr.com/ru/post/898609/


All Articles