Search code examples
c++arraysdynamic-memory-allocation

Does this make an array of pointers?


So I'm trying to make a dynamically allocated array. To do that I'm trying to make an array of pointers. I used typedef to define the pointer type and tried to create the array of pointers using this code.

emprec * arrptr = new emprec[size];

my question is, is this the correct way to create an array of pointers? If not, what would be a better way of doing so.

emprec is defined in the program as seen below

struct emprec
{
int id;
float salary;
};
typedef emprec * emprecptr;
typedef emprec arr[MAXDBSIZE];

(I am a student and I'm trying to learn more about dynamic allocation)


After the kind help of you guys on here, it was made clear that I originally made an array of emprec which would be an array of structs. I didn't want that. Changing the code to

emprecptr* DBarray = new emprecptr[dbsize];

now gives me an array of pointers.


Solution

  • Given

    struct emprec
    {
        int id;
        float salary;
    };
    

    then, no

    emprec * arrptr = new emprec[size];
    

    is not an array of pointers, but an array of emprec's. But since you also had typedef emprec * emprecptr;, then

    emprecptr * arrptr = new emprecptr[size];
    

    would be an array of pointers (to emprec). Without the typedef you would have to write it as:

    emprec* * arrptr = new emprec*[size];
    

    But as you can see, the typedef simplifies the understanding of the code and possibly, makes it easier to read.