Re: Array and Pointer Tutorial




As a matter of convenient maintenance, not a true error, it is more
dabble-proof to use sizeof *pointer rather than sizeof (type). If your
pointer's type changes, the first form stays correct, the second can
turn deceptively (and hiddenly!) broken.

All in all, that program should've looked like this:

#include <stdlib.h>

int main(void)
{
int array[5];

int* const pointer = malloc(5 * sizeof *pointer);
}

Anyway, the difference between pointers and arrays is most simply
demonstrated using the age[1]-old method of arrows and groups of boxes.

Richard

[1] I.e., in the computing world, a couple of decades

Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

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

int main(void) {
int array[5];

int *q = malloc(sizeof *array);

return 0;
}


Now, I change
int array[5];

to

double array[5];

Wouldn't the sizeof double be truncated to the sizeof int? If so, the
wouldn't this create an additional bug?

Chad

.



Relevant Pages

  • Re: problem with memcpy and pointers/arrays confusion - again
    ... int line, unsigned long *total_mem) ... That's a long pointer address... ... If sizeof > sizeof which is ... if you allocate for char with sizeof < sizeof, ...
    (comp.lang.c)
  • Re: size of a function
    ... Note that "sizeof foo" won't do this, since the argument to sizeof is one of the contexts in which a function name is *not* implicitly converted to a pointer. ...
    (comp.lang.c)
  • Re: Array and Pointer Tutorial
    ... dabble-proof to use sizeof *pointer rather than sizeof. ... pointer's type changes, the first form stays correct, the second can ... int main ...
    (comp.lang.c)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)