Reputation: 5993
char str[] = " http://www.ibegroup.com/";
char *p = str ;
void Foo ( char str[100]){
}
void *p = malloc( 100 );
What's the sizeof
str
,p
,str
,p
in the above 4 case in turn?
I've tested it under my machine(which seems to be 64bit) with these results:
25 8 8 8
But don't understand the reason yet.
Upvotes: 2
Views: 1429
Reputation: 287835
sizeof(char[])
returns the number of bytes in the string, i.e. strlen()+1
for null-terminated C strings filling the entire array. Arrays don't decay to pointers in sizeof
. str
is an array, and the string has 25 characters plus a null byte, so sizeof(str)
should be 26. Did you add a space to the value?
The size of a pointer is of course always determined just by the machine architecture, so both instances of p
are 8 bytes on 64-bit architectures and 4 bytes on 32-bit architectures.
In function arguments, arrays do decay to pointers, so you're getting the same result that you get for a pointer. Therefore, the following definitions are equivalent:
void foo(char s[42]) {};
void foo(char s[100]) {};
void foo(char* s) {};
Upvotes: 4
Reputation: 4909
in the cases the size of
char str[] = “ http://www.ibegroup.com/”
is known to be 25 (24+1), because that much memory is actually allocated.
In the case of
void Foo ( char str[100]){
no memory is allocated
Upvotes: -1
Reputation: 117681
The first is the sizeof
of an built-in array, which is the amount of elements (24 + null on the end of the string).
The second is the sizeof
of a pointer which is the native word size of your system, in your case 64 bit or 8 bytes.
The third is the sizeof
of a pointer to the first element of an array which has the same size as any other pointer, the native word size of your system. Why a pointer to the first element of an array? Because size information of an array goes lost when passed to a function and it gets implicitly converted to a pointer to the first element instead.
The fourth is the sizeof
of a pointer which has the same size as any other pointer.
Upvotes: 1
Reputation: 41357
str
is an array of 8-bit characters, including null terminator.
p
is a pointer, which is typically the size of the machine's native word size (32 bit or 64 bit).
The size taken up by a pointer stays constant, regardless of the size of the memory to which it points.
EDIT
In c++, arguments that are arrays are passed by reference (which internally is a pointer type), that's why the second instance of str
has sizeof
8.
Upvotes: 0