Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to "declare" strings in C

Tags:

c

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";
like image 485
user979009 Avatar asked Oct 04 '11 17:10

user979009


People also ask

What is the data type for string in C?

Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.

How are strings stored in C?

When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

How do you declare a string and initialize it?

To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).


1 Answers

It depends on what your needs are.

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

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).

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

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

char *str = "Here is my text";

str is now a pointer to a string of 15 characters (plus a null terminator). You cannot modify the string itself, but you can make str point 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:

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

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

like image 145
Ferruccio Avatar answered Sep 19 '22 13:09

Ferruccio