A dreadful thing

Saturday, October 4th, 2008 10:32
[personal profile] kpreid
some type *foo;
size_t count = ...;

...

foo = malloc(count * sizeof * foo);

Is it just a spacing thing?

Date: 2008-10-04 16:11 (UTC)
From: [identity profile] splogs.livejournal.com

The spacing is obviously dreadful; however, the result is what you'd expect, right? Given the following code, we can distinguish what happens in sizeof calls.


#include <stdlib.h>
#include <stdio.h>

int
main()
{
  char *foo;

  printf("type size=%u\n", sizeof *foo);
  printf("ptr  size=%u\n", sizeof foo);

  return 0;
}

Once run (on a 32-bit machine), we get the output indicated by the printf calls.

$ ./a.out 
type size=1
ptr  size=4

So, in the end, it's just a matter of knowing operators and precedence. If one does any C programming, this is always an important thing to pick up.