How to declare strings in C

Possible duplicate:
Char * and char [] memory allocation

Can someone explain to me what the difference is between these lines of code

char *p = "String"; char p2[] = "String"; char p3[7] = "String"; 

In which case should I use each of the above?

+84
c
Jan 04 '12 at 18:55
source share
4 answers

This link should satisfy your curiosity.

Basically (forgetting your third example, which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to an array.

But in the code, you can manipulate them like pointers anyway - only one, you cannot redistribute the second.

+34
Jan 04 '12 at 18:59
source share

Strings in C are represented as arrays of characters.

 char *p = "String"; 

You declare a pointer pointing to a line stored somewhere in your program (changing this line is undefined behavior) according to the C 2 ed programming language.

 char p2[] = "String"; 

You declare a char array initialized with the string "String", leaving the task to the compiler to calculate the size of the array.

 char p3[5] = "String"; 

You declare an array of size 5 and initialize it to "String". This is a mistake because "String" does not fit into 5 elements.

char p3[7] = "String"; is the correct declaration ('\ 0' is the trailing character in lines c).

http://c-faq.com/~scs/cclass/notes/sx8.html

+27
Jan 04 2018-12-12T00:
source share

You should not use the third because it is wrong. "String" takes up 7 bytes, not 5.

The first is a pointer (it can be reassigned to another address), the other two are declared as arrays and cannot be reassigned to different memory cells (but their contents can change, use const to avoid this).

+20
Jan 04 '12 at 18:58
source share
 char *p = "String"; means pointer to a string type variable. 

char p3[5] = "String" ; means that you pre-determine the size of the array, consisting of no more than 5 elements. Note that for strings null "\ 0" is also considered an element. Thus, this operator would give an error, since the number of elements is 7, so it should be:

 char p3[7]= "String"; 
+7
Jan 04 '12 at 19:01
source share



All Articles