Re: Array and Pointer Tutorial
- From: rlb@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos)
- Date: Thu, 11 May 2006 07:01:03 GMT
"Tomás" <NULL@xxxxxxxxx> wrote:
Some programmers treat arrays just like pointers (and some even think that
they're exactly equivalent). I'm going to demonstrate the differences.
Firstly, let's assume that we're working on a platform which has the
following properties:
1) char's are 8-Bit. ( "char" is synomonous with "byte" ).
A char is _always_ a byte. What you mean is that you are assuming a char
(and therefore also a byte) to be equal to an octet.
2) int's are 32-Bit. ( sizeof(int) == 4 ).
3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).
First let's make two declarations:
int main(void)
{
int array[5];
int* const pointer = (int*)malloc( 5 * sizeof(int) );
*Boing* and here the demonstration crashes.
Never cast malloc(). It is not necessary. void *s can be freely
converted to and from any object pointer type.
Never use malloc() (or any other function, for that matter) without a
proper declaration in scope. It forces your compiler to assume that the
function returns an int, which malloc() clearly does not.
Note that the first error hides the second. The combination of the two
can result in garbage being assigned to your pointer.
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
.
- Follow-Ups:
- Re: Array and Pointer Tutorial
- From: Chad
- Re: Array and Pointer Tutorial
- Prev by Date: Re: dynamic mem alloc q
- Next by Date: Re: mirror image of tree
- Previous by thread: simplifying c code with function pointers
- Next by thread: Re: Array and Pointer Tutorial
- Index(es):
Relevant Pages
|