Skip to main content
GameDev.net gamedev.net
🔒 Locked

dynamically allocated arrays

Started by popcorn Mar 2, 2004 at 9:07 AM 3 replies 350+ views
Original Post
popcorn
popcorn
Hi can someone explain to me whats going on in one part of this program.
/* Program 9.2 from PTRTUT10.HTM   6/13/97 */

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

int main(void)
{
    int nrows = 5;     /* Both nrows and ncols could be evaluated */
    int ncols = 10;    /* or read in at run time */
    int row;
    int **rowptr;
    rowptr = malloc(nrows * sizeof(int *));
    if (rowptr == NULL)
    {
        puts("\nFailure to allocate room for row pointers.\n");
        exit(0);
    }

    printf("\n\n\nIndex   Pointer(hex)   Pointer(dec)   Diff.(dec)");

    for (row = 0; row < nrows; row++)
    {
        rowptr[row] = malloc(ncols * sizeof(int));
        if (rowptr[row] == NULL)
        {
            printf("\nFailure to allocate for row[%d]\n",row);
            exit(0);
        }
        printf("\n%d         %p         %d", row, rowptr[row], rowptr[row]);
        if (row > 0)
        printf("              %d",(int)(rowptr[row] - rowptr[row-1]));
    }

    return 0;
}
Can someone explain to me why the difference between the pointer addresses is 12 in this expression (rowptr[row] - rowptr[row-1])); How about them apples? [edited by - popcorn on March 2, 2004 10:11:01 AM]
How about them apples?
Doughboy
Doughboy
The difference beteween those two values is arbitrary, really. They are created by two seperate calls to malloc, and malloc does NOT allocate blocks sequentially in memory.
The difference may be 12 once, but it could very possibly (and likely) be different the next time you run it.
popcorn
popcorn
Thanks Doughboy, I can understand that the memory will not be allocated sequentially. Its just that everytime I ran the program it was always 12 that I got back although I did notice that the memory addresses were different each time.

How about them apples?
How about them apples?
SiCrane
SiCrane
Chances are that because no deallocation is occuring the successive memory allocations, the allocations are being tightly packed, so you have minimual fragmentation: hence the difference comes out the same every time. However, in a situation when you overrun the initial heap size, even with no deallocation, chances are that a difference between allocations will show up as larger than 12 at some point in time.
popcorn
popcorn
Thanks for the reply SiCrane. I just want to make sure I understand what is happening in this situation.


How about them apples?
How about them apples?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.