Array question

Robert Nelson Gasch rg2c+ at andrew.cmu.edu
Sun Feb 10 14:51:08 AEST 1991


Hi,
my programming background is Pascal and I've been using C for about
half a year by now. Coming from Pascal, the way arrays and pointers
are related is somewhat confusing. I have a question: 

I can define an array as

    int this_array[10];
    this_array [0] = 1;

which is straight forward and easily understandible. I can also do this,

    int *this_ptr;
    this_ptr = (int *) malloc (10 * sizeof (int));

which explicitly allocates the space for 10 integers. Now, here comes
the question: 
What happens if I do the following? Basically I don't really understand
*why* this works:

    int *this_ptr;
    this_ptr [0] = 1;
    this_ptr [1] = 2;
    . . . 
    this_ptr [9] = 10;

This works fine, but I really don't know why?? It seems you're using
memory to store an array which was never really allocated. If anybody
could briefly explain what exactly happens when you do this, I'd be
greatly abliged as at this point I'm mystified. 

Thanks alot --> Rob
rg2c at andrew.cmu.edu



More information about the Comp.lang.c mailing list