Tutorial :strcat query (string.h)


First off : STRCAT :

Cplusplus - strcat

When clearly the definition says :

char * strcat ( char * destination, const char * source );  

Why'd they use char str[80] in the example??? Shouldn't they have used a character pointer?


That is because arrays decay into pointers in C/C++. If you define char s[80] the value of s will be the address of the first character i.e &s[0]


array can also be used as pointer. what strcat needs is the pointer to a memory in which it copies the destination string. In this case str[80] will give you the memory that can hold 80 chars.


char str[80];  

declares an array of 80 characters. However, in C and C++, arrays are implicitly converted to pointers. When you pass an array to a function (such as strcat), it automatically "decays", forming a pointer to the first element of the array.

That's not the same as saying that arrays and pointers are the same thing. They aren't. For example, sizeof() yields different results on the above array, and a char*.


An array is, strictly speaking, a pointer to the beginning of a block of memory. So str is a char * that points to the beginning of 80 characters.

When you index into an array, say position 53, the following is equivalent: str[53] is the same as *(str + 53) as str is just a char * and adding 53 to a character pointer will return a pointer so to get the value inside you have to use an asterisk to dereference the pointer. In effect array notation just makes code more readable in certain circumstances.

Actually a great little trick with arrays of char is when you want to skip over some leading text when copying a string. E.g. let's say your array str[80] contains the string "1023: error in code!". And you want to display just the string without the number in front. In this case you could say printf( "%s", str + 6 ) and only "error in code!" would be printed.


char str[80];  

Edit: Opps, I rushed my answer. As dribeas says the statement declares an array and str can be implicitly converted into a pointer when it is used. For instance:


is an invalid operation while:

char* ptr;  ++ptr;  


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »