difference between char * and char array in c

Suppose we wish to store “Hello”. We may either store it in a string or we may ask the C compiler to store it at some location in memory and assign the address of the string in a char pointer. This is shown below:
char str[ ] = "Hello" ;
char *p = "Hello" ;

 

1. Assignment :
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to another, whereas, we can assign a char pointer to another char pointer. This is shown in the
following program.

main( )
{
        char str1[ ] = "Hello" ;
        char str2[10] ;
        char *s = "Good Morning" ;
        char *q ;
        str2 = str1 ; /* error */
        q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings, such an operation is perfectly valid with char pointers.

main( )
{
        char str1[ ] = "Hello" ;
        char *p = "Hello" ;
        str1 = "Bye" ; /* error */
        p = "Bye" ; /* works */
}

2. Read-only parts of the memory :

char * and char [] both are used to access character array, Though functionally both are same , they are syntactically different. See how both works in order to access string.

char *s = "Hello world";
will place Hello world in the read-only parts of the memory and making s a pointer to that, making any writing operation on this memory illegal. While doing:

char s[] = "Hello world";
puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Thus making s[0] = 'J';legal.











No comments:

Post a Comment