Wednesday, September 1, 2010

Difference in string and pointers

Consider the assignments below:

char my_string[40] = "hello";
char my_name[] = "hello";
char *my_name = "hello";
Is there a difference between these? The answer is.. yes but after all they hold string called hello.
So where they are different?

In case1, the statement would allocate space for a 40 byte array and put the string in the first 6 bytes (five for the characters in the quotes and a 6th to handle the terminating '\0').

Consider the case 2: where we have only 6 characters assigned where the compiler would count the characters, leave room for the nul character and store the total of the 6 characters in memory the location of which would be returned by the array name, in this case my_name.

In case3 , the compiler store the strings of 6 bytes in the memory we don't know. So this is the array notation 6 bytes of storage in the static memory block are taken up, one for each character and one for the terminating nul character. But, in the pointer notation the same 6 bytes required, plus N bytes to store the pointer variable my_name (where N depends on the system but is usually a minimum of 2 bytes and can be 4 or more). 
For more read here.

These cases have their own significance.
Eg.
char p[] = "hello"; //This methods save space compared to char [40]= "hello";
char* p = "hello";//This methods save space compared to char [40]= "hello";

But consider the case of strcpy function....where we may have to copy one string larger than these 6 bytes of hello ... so what to do? To get to see the idea of problem see here.
So in case of
char p[] = "hello";
...
strcpy(p,"hello world"); 
We may get core dump in this case. Similar will the case hold in case of strcat, if we have these kind of strings.

In case of char *p = "hello";
we mean that string is hello somewhere in the memory and p points to it...but that string is
const char* and when we assign higher length value by strcpy or try to change it even will flash error message.
even this is wrong
strcpy("hello","world");
Because both "hello" and "world" are const strings, string literals.

No comments:

Post a Comment