Thursday, July 21, 2011

The Ugly Thing about char [], char *, const char *, char * const and char const *

These concepts seem simple, but mistake can be made if you haven't thoroughly understood them.

  • is following code correct?
foo()
{
char a[]= "I HATE U!";
a[0] = 'U';
}
        Yes,  array a[] will be allocated on stack and a[0] just modifies the first character.

  • is following code correct?
foo()
{
char *a = "I HATE U!";
a[0] = 'U';
}
        Compiler won't complain, but the program will crash. The reason is "I HATE U!" is a constant that will be allocated in the constant memory region.  If we try to modify its value thru pointer a, you will be hit by seg fault.
        However,  initializing the variable  takes a huge performance and space penalty for the array (using char a[] = "XXXX"). Only use the array method if you intend on changing the string, it takes up space in the stack and adds some serious overhead every time you enter the variable's scope. Use the pointer method otherwise.

  • is following code correct?
foo()
{
cont char *a = "I HATE U!";
a[0] = 'U';
}
        No, compiler will complain.  a is a pointer points to char constant, you can modify what a points to (a's value), but you can't modify the content of the address that a points to (*a's value).

  • is following code correct?
foo()
{
char * const a = "I HATE U!";
a++;
}
        No, compiler will complain.  a is a constant pointer, therefore you can'y modify what a points to (a's value). But you can modify the content of the address that a points to (*a's value) if that address is valid to access. In the above example, the address is not valid to access.

  • is following code correct?
foo()
{
char const *a = "I HATE U!";
a[0] = 'U';
}
        No, compiler will complain. char const *a is the same as const char * a. 

No comments:

Post a Comment