Search code examples
cpointersabstract-data-type

Using Malloc() to create an integer array using pointer


I'm trying to create an integer array using the defined ADT below using the malloc() function. I want it to return a pointer to a newly allocated integer array of type intarr_t. If it doesn't work - I want it to return a null pointer.

This is what I have so far -

//The ADT structure

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

//the function 

intarr_t* intarr_create( unsigned int len ){

    intarr_t* ia = malloc(sizeof(intarr_t)*len);
    if (ia == 0 )
        {
            printf( "Warning: failed to allocate memory for an image structure\n" ); 
            return 0;
        }
    return ia;
}

The test from our system is giving me this error

intarr_create(): null pointer in the structure's data field
stderr 
(empty)

Where abouts have I gone wrong here?


Solution

  • It can be inferred from the error message, intarr_create(): null pointer in the structure's data field, that data fields of each struct are expected to be allocated.

    intarr_t* intarr_create(size_t len){
        intarr_t* ia = malloc(sizeof(intarr_t) * len);
        size_t i;
        for(i = 0; i < len; i++)
        {
            // ia[len].len = 0; // You can initialise the len field if you want
            ia[len].data = malloc(sizeof(int) * 80); // 80 just for example
            if (ia[len].data == 0)
            {
                fputs("Warning: failed to allocate memory for an image structure", stderr); 
                return 0;
            }
        }
        return ia; // Check whether the return value is 0 in the caller function
    }