On May 7, 10:40=A0pm, Keith Thompson <ks...@[EMAIL PROTECTED]
> wrote:
> Bart <b...@[EMAIL PROTECTED]
> writes:
> > On May 6, 11:45=A0am, "Kevin" <yushuma...@[EMAIL PROTECTED]
> wrote:
> >> Source:
> >> #include <stdio.h>
> >> #include <ctype.h>
> >> void main()
> >> {
> >> =A0 =A0 char a[]=3D"this is the beautiful world!";
> >> =A0 =A0 char b[20];
> >> =A0 =A0 strcpy(b,a);
> >> =A0 =A0 printf("char array b size is(%d),The content of b
is:%s\n",size=
of(b),b);
> >> =A0 =A0 if(strcmp(a,b)=3D=3D0)
> >> =A0 =A0 =A0 =A0printf("a equal to b!\n");
>
> >> }
>
> >> Now , question as follows:
>
> >> 1. Why "b" size unequal "a" size , but "b" can output "a" content?
> >> 2. Why "if(strcmp(a,b)=3D=3D0)" is true?
>
> > a and b are different types:
>
> Yes.
>
> > a is a pointer to a string
>
> No, a is an array of type char[29] (the length of the literal used to
> initialize it plus 1 for the trailing '\0').
Yes, of course, I read it as char *a (I think char a[] is pointer in
some other context).
> > b /is/ a string.
>
> No, b is an array of type char[20]. =A0An array can *contain* a string.
So some informality.. Here the intention is clearly a string.
>
> A "string" in C is a a data format, not a data type.
>
> > But a can obviously point to a string identical to what's in b.
>
> The object named ``a'' can't point to anything, since it's an array,
> not a pointer. =A0However, the expression ``a'', in most but not all
> contexts, has the value of a pointer to (the address of) the first
> element of the object named ``a''.
>
> > The size of a will be 4 or whatever, the size of b will be 20
> > (although it should be more in this case otherwise your "this is..."
> > string will overflow it).
>
> No, sizeof a =3D=3D 20.
Don't know about that, it seems a bit more. But different from sizeof
b anyway, which was the original confusion.
>
> > strcmp() compares two pointers to strings; but b is automatically
> > converted to such a pointer, thanks to the way C handles arrays.
Well if a and b are both arrays, then the reason why strcmp matches
them but sizeof is different is a little different!
(strcmp() only matches characters up to the nul terminator, ignoring
any trailing characters in the array that still contribute to the
sizeof property.)
--
Bartc


|