Re: embedded questions!!!
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Fri, 13 Jan 2006 19:12:20 GMT
Richard Henry wrote:
"John B" <spamj_baraclough@xxxxxxxxxxxxxxxxxxx> wrote in message news:43c7b8d3$0$819$4c56ba96@xxxxxxxxxxxxxxxxxxxxxxxxx
The two declarations:
char str1* = "JHONSON";
I'll assume that's supposed to be 'char *str1 = "JHONSON";'...
and
char str2[] = "JHONSON";
both allocate space for a modifiable string. The difference being that the first one also creates a pointer to that string.
Isn't str2 also a pointer?
Nope, it's an array. If it helps to make things clearer, sizeof(str1) will be different than sizeof(str2). In particular:
sizeof(str1) == sizeof(char *)
and
sizeof(str2) == strlen(str2)+1That should help make it clearer that str1 and str2 are different types. If you were to give them names, str1's type would be "char *" and str2's type might be "char[8]". One is a pointer and the other is an array.
That may not make much sense, but think for a moment about how an int can be automatically converted to a float:
int i = 1; float f = 3.14159;
printf ("%g", i + f);What's going on here is that the compiler sees an expression where the operator (in this case "+") has two arguments which are different types. It then implicitly converts the integer into a floating point value when generating the code that will correspond to that expression.
A similar thing happens when arrays are used where a pointer value is needed. The compiler thinks "this isn't a pointer, but since it's an array, I can create a pointer value from it".
Another way they differ, if I understand correctly is that this would be legal:
str1 = (char *) "another string";
but this would not be:
str2 = (char *) "another string";
The reason is this: str1 is just a pointer, so it can take on any value.
But str2 is the array that contains { 'J', 'H', 'O', 'N', 'S', 'O', 'N', 0 },
and how are you supposed to assign a pointer to that?- Logan .
- References:
- Re: embedded questions!!!
- From: Rufus V. Smith
- Re: embedded questions!!!
- From: Chuck F.
- Re: embedded questions!!!
- From: John B
- Re: embedded questions!!!
- From: Richard Henry
- Re: embedded questions!!!
- Prev by Date: Re: embedded questions!!!
- Next by Date: Re: embedded questions!!!
- Previous by thread: Re: embedded questions!!!
- Next by thread: Re: embedded questions!!!
- Index(es):
Relevant Pages
|