[Courses] sizeof operator
James Sutherland
james at deadnode.org
Tue Feb 14 17:27:11 UTC 2012
On 14 Feb 2012, at 17:03, millward wrote:
> When I define an integer array, such as
> int array[40];
> the sizeof operator can detect the correct
> number of bytes which make up the array
> int number_of_bytes = sizeof( array );
It isn't "detecting" anything as such - you told it the array is "40 ints long", the compiler knows how big an 'int' is in bytes. It's the equivalent of asking a sales assistant "how long is this ten foot rope in inches?" - the assistant won't need to look at the rope itself, just know that a foot is 12 inches making the rope 120 inches long.
> How does the sizeof operator do this ?
> I can see how sizeof finds the correct byte
> size of a char array since it ends
> with a nul '\0' but as far as I know, the integer
> array has no special character to end it.
> How does this sizeof operator work ?
If you try asking: "sizeof(int)" you might see what's going on. The compiler isn't measuring the size of a particular variable which holds an int - it *knows* that an int is defined to be a certain number of bytes (usually 4 or 8) on this system.
sizeof never looks at the variable itself - as "sizeof(int)" shows, there might not even be one. It's strlen which looks for a terminating null on strings.
#include <string.h>
#include <stdio.h>
int main(int argc,char **argv)
{
char woof[10]="meow";
printf("sizeof(woof)=%ld\n",sizeof(woof));
printf("strlen(woof)=%ld\n",strlen(woof));
printf("sizeof(int)=%ld\n",sizeof(int));
return 0;
}
Output on my machine:
$ gcc -o scratch{,.c} -Wall ; ./scratch
sizeof(woof)=10
strlen(woof)=4
sizeof(int)=4
I declared 'woof' to be ten chars long, so sizeof reports that as the size - even though it contains 'meow' and a terminating null; it's strlen which counts the characters before the null and answers 4.
James.
More information about the Courses
mailing list