I red the answers to a similar question where the matter is extensively and straighforwardly discussed. I would like to be sure of the correct interpretation i gave them.
For example, my textbook states, at exercise 6.24, that "The sizeof operator can be used to find the number of bytes needed to store a type or an expression. When applied to arrays, it does not yield the size of the array."
#include<stdio.h>
void f(int *a);
int main(){
char s[] = "deep in the heart of texas";
char *p = "deep in the heart of texas";
int a[3];
double d[5];
printf("%s%d\n%s%d\n%s%d\n%s%d\n",
"sizeof(s) = ", sizeof(s),
"sizeof(p) = ", sizeof(p),
"sizeof(a) = ", sizeof(a),
"sizeof(d) = ", sizeof(d));
f(a);
return 0;
}
void f(int *a){
printf("In f(): sizeof(a) = %d\n", sizeof(a));
}
Even so, it does not appear that obvious to me. Hence, I would like to briefly discuss the output with you:
sizeof(s) = 27
sizeof(p) = 8
sizeof(a) = 12
sizeof(d) = 40
In f(): sizeof(a) = 8
Then:
sizeof(s) = 27
In this case, 27
is the number of bytes of that s
is composed of, being each char
composed of one byte. This appear in contrast to the definition of sizeof
because it returns what appear to be the _size_of an array. At this point, am I correct thinking that char s[] = "deep in the heart of texas"
is considered as an expression?
sizeof(p) = 8
Here, we have a pointer char *
. Since sizeof "finds the number of bytes needed to store a type", I assume that a pointer char *
is stored in 8 bytes of memory. Am I correct?
sizeof(a) = 12 and In f(): sizeof(a) = 8
This case make me particularly unsure. The only relevant difference I found is that in f()
the array a
is passed as a parameter : a pointer to its base. As before, a pointer is stored in 8 bytes of memory. Am I correct? If so, 12
has to be considered to be the amount of memory needed to store the expression int a[3]
?
sizeof(d) = 40
Again, it appears to return the dimension of the array d
, that is, five sections of 8
bytes each. But, again, we are not talking about an array, rather we are considering an expression double d[5]
. Is it correct?
Thanks for sharing with me your knowledge and experience!