Thread: Create array of pointers dynamically

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    23

    Create array of pointers dynamically

    Hello,

    I'm trying to dynamically create an array whose contents are pointers to a struct.

    Statically, I have something like this:

    Code:
    typedef struct {
        ...
    } my_struct;
    
    int main(){
        my_struct *array[10];
        ...
    }
    which works fine. I'd like to change the static allocation to a dynamical one, but I'm always getting segfaults. How to do it?

    Thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Search the forum for something like "dynamic 2D arrays" and you should get a bunch of stuff.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Use malloc()
    Code:
    my_struct **array;
    
    array = malloc(sizeof(*my_struct) * number_of_elements_you_want);
    That will allocate so many pointers. But you may also want to allocate memory to hold the structs. That needs more mallocs per struct.
    Code:
    array[i] = malloc(sizeof(my_struct));
    Then you access these by array[i]->struct_element_name

    Maybe you just want an array of structs:

    Code:
    my_struct *array;
    array = malloc(sizeof(my_struct) * number_of_elements_you_want);
    Then you access these by array[i].struct_element_name
    Last edited by nonoob; 04-01-2011 at 09:45 PM.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by quzah View Post
    Search the forum for something like "dynamic 2D arrays" and you should get a bunch of stuff.
    Huh? The question is asking about dynamically allocating an array of pointers, not 2D arrays. I agree that 2D arrays often involve arrays of pointers, but the reverse is not true.

    In answer to the original question, assuming you want an array of length n, it is possible to use VLAs

    Code:
         int n;
          /*   something that sets a useful value of n */
    
          my_struct *array[n];
             /*   populate the array  */
             /*   do something with the array  */
    This only works with C99. If using C89 (which a lot of compilers still do) it is necessary to use
    Code:
         int n;
         mystruct **array;
          /*   something that sets a useful value of n */
    
         array = malloc(n*sizeof(*array));
         if (array == NULL)
         {
             complain_bitterly();
         }
         else
         {
             /*   populate the array  */
             /*   do something with the array  */
    
             free(array);
         }
    
         /*   do not use array again   */
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by grumpy View Post
    Huh? The question is asking about dynamically allocating an array of pointers, not 2D arrays. I agree that 2D arrays often involve arrays of pointers, but the reverse is not true.
    Tell me incredibly confused one, how do you dynamically make a 2D array?
    Quote Originally Posted by grumpy View Post
    Code:
         int n;
         mystruct **array;
          /*   something that sets a useful value of n */
    
         array = malloc(n*sizeof(*array));
         if (array == NULL)
         {
             complain_bitterly();
         }
         else
         {
             /*   populate the array  */
             /*   do something with the array  */
    
             free(array);
         }
    Oh, look, you made the first half of a dynamic 2D array! Wow that was a totally surprising and unexpected way of doing what he just said he wanted done! I am completely stunned by your unique solution!

    This is me openly mocking you.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Grumpy's reply took one way of thinking about it, and Quzah's took a slightly different way, but the end result is the same - he gets an array of pointers, to an array of pointers to strings.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's the exact same piece of code both ways of looking at it.

    If you can't understand what dynmaic 2D arrays have to do with making an array of pointers, then you don't understand how to actually make a dynamic 2D array.


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    My point is that a 2D array is a more specialised construct than an array of pointers. The OP asked about the latter.

    Although there is a relationship between arrays of pointers and 2D arrays, it is possible to create and use an array of pointers without creating a 2D array.

    Quote Originally Posted by quzah View Post
    This is me openly mocking you.
    Which just adds support to my view that you are a ........wit.
    Last edited by grumpy; 04-02-2011 at 04:35 PM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by grumpy View Post
    My point is that a 2D array is a more specialised construct than an array of pointers.
    It's not more specialized. It's the exact same thing. It's an array of pointers that end up pointing to things.
    Quote Originally Posted by grumpy View Post
    Although there is a relationship between arrays of pointers and 2D arrays, it is possible to create and use an array of pointers without creating a 2D array.
    Yes. You can make an array of uninitialized pointers. And as soon as you make them point at something, you've got yourself a 2D array.

    The point is, instead of us typing the same exact reply 1000 times, if he knows what to look for, this question has been answered countless times before.


    Quzah.
    Last edited by quzah; 04-02-2011 at 04:58 PM.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by quzah View Post
    And as soon as you make them point at something, you've got yourself a 2D array.
    That is not true.

    The conventional definition - in mathematics and in computer science - of a two-dimensional array is a collection in which individual elements can be accessed using two subscripts (i.e. array[i][j] syntax in C, array(i,j) in Fortran, etc).

    If each pointer in the array was initialised to point to the head of a linked list, that array of pointers is not a 2D array. Using the array[i][j] syntax will give undefined behaviour (for any non-zero j) although, in C, it will sail merrily past the compiler.
    Quote Originally Posted by quzah View Post
    The point is, instead of us typing the same exact reply 1000 times, if he knows what to look for, this question has been answered countless times before.
    My point is that the question you have addressed is not the one asked. The question you answered (or, gave a pointer for) is a particular case of the one asked.

    If someone asked you for directions to a greengrocer (a store that sells multiple types of fruit and vegetables), then presumably you would see nothing wrong with giving directions to a stall that only sells apples. However, your answer would be completely useless to someone who wanted to buy oranges and bananas.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by grumpy View Post
    The conventional definition - in mathematics and in computer science - of a two-dimensional array is a collection in which individual elements can be accessed using two subscripts (i.e. array[i][j] syntax in C, array(i,j) in Fortran, etc).

    If each pointer in the array was initialised to point to the head of a linked list, that array of pointers is not a 2D array. Using the array[i][j] syntax will give undefined behaviour (for any non-zero j) although, in C, it will sail merrily past the compiler.
    I hope you won't mind terribly while I prove you wrong again.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    int main( void )
    {
        char **foo;
        char c;
        foo = malloc( N * sizeof *foo ); /* make an array of N char* */
    
        foo[ 0 ] = &c;
        foo[ 0 ][ 0 ] ='a';
        
        printf( "\'%c\'", c );
    
        free( foo );
        return 0;
    }
    Yay me.
    Quote Originally Posted by grumpy View Post
    My point is that the question you have addressed is not the one asked. The question you answered (or, gave a pointer for) is a particular case of the one asked.
    My point is that you completely missed the correlation to making a dynamic 2D array and making an array of pointers. You can't make a dynamic 2D array without making a array of pointers.
    Quote Originally Posted by grumpy View Post
    If someone asked you for directions to a greengrocer (a store that sells multiple types of fruit and vegetables), then presumably you would see nothing wrong with giving directions to a stall that only sells apples. However, your answer would be completely useless to someone who wanted to buy oranges and bananas.
    That's a terrible analogy. He wanted to know how to paint. I showed him how to paint a car.


    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by quzah View Post
    I hope you won't mind terribly while I prove you wrong again.
    I wouldn't mind, but your example does not achieve that.
    Quote Originally Posted by quzah View Post
    My point is that you completely missed the correlation to making a dynamic 2D array and making an array of pointers. You can't make a dynamic 2D array without making a array of pointers.
    I didn't miss the correlation. I don't consider that correlation particularly important in this case. Not all arrays of pointers are 2D arrays.
    Quote Originally Posted by quzah View Post
    That's a terrible analogy. He wanted to know how to paint. I showed him how to paint a car.
    Michelangelo would be spinning in his grave.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by grumpy View Post
    I wouldn't mind, but your example does not achieve that.
    Sure it does. You expressly pointed out how 2D arrays means you access via [][], and I showed you that what you said can still be accessed the same way. It doesn't matter what you point at in your array of pointers, I can still access it via [][0].
    Quote Originally Posted by grumpy View Post
    Michelangelo would be spinning in his grave.
    Fortunately for us, there are no well known deceased fruit stand operators


    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Well, if you want to create array of char dynamically, declare pointer to char, and allocate with malloc.

    To create array of type T dynamically, declare pointer to type T and allocate with malloc/...

    Since OP wants array of pointers dynamically, he needs pointer to pointers.

  15. #15
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by quzah View Post
    It doesn't matter what you point at in your array of pointers, I can still access it via [][0].
    Are you also claiming that, if the pointers point at the head of a linked list, that you can access other elements of each linked list using array subscripts?
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamically creating an array of pointers
    By cs32 in forum C Programming
    Replies: 4
    Last Post: 02-06-2008, 09:42 AM
  2. how to create an array of pointers
    By Dan17 in forum C++ Programming
    Replies: 12
    Last Post: 04-26-2006, 08:02 AM
  3. array of pointers to structs
    By stumon in forum C Programming
    Replies: 7
    Last Post: 03-24-2003, 07:13 AM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Array of pointers help
    By Unregistered in forum C Programming
    Replies: 10
    Last Post: 02-14-2002, 12:37 PM