#include <stdio.h>
int main()
{
char *a[4]={ "oracle", "java"};
char *p=a;
printf("%d, %d",sizeof(a),sizeof(char *));
printf("\n The size of p=%d",sizeof(p));
getch();
return 0;
}
wats the output?
16,4
The size of p=4
Why?? Coz we all know tht "a" is a constant point which is pointing to the first element of the array. Alright? so sizeof(a) shud be 4 (the size of a memory element on 32 bit OS) ... instead the sizeof(a) takes in the entire array into account. However, as u can see p is also a pointer which is pointing to the same address as "a". And sizeof(p) is 4. :-S
PS: Am using devc++
a is a static array of 4 character pointers, thus the size of a is 4 * the size of a character pointer, since sizeof will resolve to the size of a whole array if the object it is being used on is a static array [one that is not assigned by 'new' or malloc]. p is a character pointer that you've assigned to point to the first element of the character pointer array, so for that reason, p and a are not even of the same type [but are both pointers, and thus have a size of 4 per element]. Other compilers will actually flag this as an error, demanding explicit casting from what is effectively a char** to a char* [though some compilers will call it a cast from char*[4] to char*, but they are nearly equivilant].
a[0] and p are of the same type. The type difference has nothing to do with the size difference in the case, the size difference is caused by a being a static array of elements each of size 4 [and 4 of them, thus 16]
I always confuse when I deal with pointer, So if I'm wrong please correct me. In this case I think char* a[4] have 4 element of pointer (char* a[0] to char* a[3]) so sizeof(a) must be equal to sizeof(char*) * 4. but char* p is the pointer-to-pointer it only point to the first pointer element which mean p point to the a[0] which make sizeof(p) = sizeof(char*).
DinGY
Yesterday is history.Tomorrow is a mystery. Today is a gift"
Wow... Thanks a lot guys! Really cleared tht up! :D Quick question, doesnt the array name store the address of the 1st element? Also, acc to what you all have said, "a" basically refers to the entire array implicitly?
char *a[4]={ "oracle", "java"}; const char *p=a; printf("%d, %d",sizeof(a),sizeof(char *)); printf("\n The size of p=%d",sizeof(p)); printf("\n The address of a=%d, p=%d",a,p); printf("\n the address of 1st element=%d",&a[0]); getch(); return 0;
The output statements prints memory addresses which are the same.
Quote:Original post by bodhisatva_b Quick question, doesnt the array name store the address of the 1st element?
The array name stores the elements in the array. When used in a pointer context, the name of the array is implicitely converted to a pointer to the first element. That doesn't mean it IS a pointer though, only that it can (with some restrictions) be used as one.