Re: Array and Pointer Tutorial
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: 11 May 2006 18:11:08 +0200
Chad wrote:
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?
You have not followed the suggested practice of using sizeof *pointer being assigned to. Your example should have been:
#include <stdlib.h>
int main(void) {
int array[5];
int *q = malloc(sizeof *q);
return 0;
}
Or, if you want array and q to always be the same type, you could have used:
#include <stdlib.h>
int main(void) {
int array[5], *q = malloc(sizeof *q);
return 0;
}
I really can't see why you would think of using sizeof some other object.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
.
- Follow-Ups:
- Re: Array and Pointer Tutorial
- From: Chad
- Re: Array and Pointer Tutorial
- References:
- Re: Array and Pointer Tutorial
- From: Richard Bos
- Re: Array and Pointer Tutorial
- From: Chad
- Re: Array and Pointer Tutorial
- Prev by Date: Re: a struct parser
- Next by Date: Re: libclc - from Boost thread
- Previous by thread: Re: Array and Pointer Tutorial
- Next by thread: Re: Array and Pointer Tutorial
- Index(es):
Relevant Pages
|