allocating for an array of pointers

Discussion in 'C Programming' started by Erik S. Bartul, Feb 21, 2004.

  1. lets say i want to fill up a multidimentional array, but i wish to allocate
    memory for it on the fly.

    i assume i declare,
    char **a;

    but how do i allocate memory for the pointers, so i can then allocate to the
    pointers to which those pointers point?

    essentially lets say i during runtime deturmine i must allocate space for 60

    a = malloc(size of(char *) * 60);

    what is this in effect allocating for?

    and subsequently when i wish to allocate memory for a pointer to which one
    of the pointers point,

    a[0] = malloc(128); /* to allocate to the first pointer in the array of
    pointers, 128 bytes */

    im probably overlooking something very simple, and it comes to mind that ive
    been in this pickle awhile back... i just cant seem to remember what that
    solution was. and i have read over the C faq.
    Erik S. Bartul, Feb 21, 2004
    1. Advertisements

  2. Erik S. Bartul

    David Rubin Guest

    int n, m, i;

    /* read n and m */
    a = malloc(n * sizeof *a); /* allocates n char* (type of *a) */
    for(i=0; i < n; i++){
    /* allocates m char (type of *a) */
    a = malloc(m * sizeof *a);

    This allocates n x m chars.


    David Rubin, Feb 21, 2004
    1. Advertisements

  3. i appologize for the hasty post, the allocation method i was using worked
    fine... it was an error elsewhere in the code. i should have debugged for
    awhile before assuming i messed up on the allocation :p
    Erik S. Bartul, Feb 21, 2004
  4. Erik S. Bartul

    Lewis Bowers Guest

    Have you read and comprehended faq question 6.16?
    It is located at:

    This question does a good job on explaining various ways of allocating a
    two-dimensional array.
    Lewis Bowers, Feb 21, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.