Bart said:
Source:
#include <stdio.h>
#include <ctype.h>
void main()
{
char a[]="this is the beautiful world!";
char b[20];
strcpy(b,a);
printf("char array b size is(%d),The content of b is:%s\n",sizeof(b),b);
if(strcmp(a,b)==0)
printf("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)==0)" 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').
No, b is an array of type char[20]. An array can *contain* 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. However, 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 == 20.
strcmp() compares two pointers to strings; but b is automatically
converted to such a pointer, thanks to the way C handles arrays.
I think the other errors in the program have already been pointed out,
but ...
Drop the ``#include <ctype.h>''; it's not needed.
Add ``#include <string.h>''; it *is* needed.
Change ``void main()'' to ``int main(void)''.
Change ``char b[20];'' to, for example, ``char b[30];''.
In the printf call, change ``sizeof(b)'' to ``(int)sizeof b'';
the "%d" format requires an int, not a size_t.
Before the closing brace, add ``return 0;''.
Enable warnings in your compiler, and buy some whitespace (it's really
cheap).