3

I have been given a .o file which creates a box_t ** and I have to use it. Now, I don't know if it is case 1:
an pointer to an array of box_t or
case 2:
an pointer to an array of box_t *

I wrote a simple code myself in creating box_t** in both the ways and accessed differently. It seems to be working fine in both the cases. Now, given a box_t **, and size_t n, number of elements in it, is it possible to know if it is case 1 or case 2 without any further information.

struct box_tag{
    int pencils;
    int pens;
};

typedef struct box_tag box_t;

box_t boxarray[10] = {{1,2},{3,4},
         {5,6},{7,8},
         {9,10},{11,12},
         {13,14},{15,16},
         {17,18},{19,20}};

box_t ** box_bundle;

Creation Version1:

box_t** create_dp(void)
{
  box_bundle = (box_t **)malloc(sizeof(box_t **));
  *box_bundle = boxarray;
}

Accessing Version 1:

int main ()
{
  box_t * tmp = *box_bundle;

  for (int i =0; i<10; i++)
    {
      printf("%d\n",tmp[i].pencils);
    }

  return 0;
}

Creation Version 2:

box_t** create_dp (void)
{
  box_bundle = (box_t **)malloc(sizeof(box_t **));
  *box_bundle = (box_t *)malloc (sizeof(box_t *) * 10);

  for(int i=0; i<10;i++)
    {
      *(box_bundle +i )  = &boxarray[i];
    }
}

Accessing Version 2:

int main ()
{
  create_dp();

  for(int i=0; i<10; i++)
    {
      box_t * tmp =*box_bundle++;
      printf("pencils %d \n", tmp->pencils);
    }

  return 0;
}

1 Answer 1

1

Both cases are incorrect. You can't use a box_t** to point at any array. Nor can it point to an array of type box_t boxarray[10], because they are incompatible types. There is no need for several levels of indirection anywhere in your code.

You can however use a box_t* to point at the first element in an array, and that's what your code does here: *box_bundle = boxarray;. But in an obfuscated way.

Correct code should be: box_t* box_bundle;. If it should point at the original array, there is no need for malloc. If it should hold a copy of the original array, you need to alloc and copy the data:

box_t* box_bundle = malloc (sizeof(*box_bundle)*10);
memcpy(box_bundle, boxarray, sizeof boxarray);
2
  • My main query is given a box_t **, and size_t n, number of elements in it, how should I access it?
    – RRON
    Commented Dec 5, 2018 at 11:29
  • @sniper As written in the answer, "You can't use a box_t** to point at any array.". You can however use it to emulate a 2D array, but that's not the case here either. Just forget all about box_t**, it is the wrong tool for a different problem.
    – Lundin
    Commented Dec 5, 2018 at 11:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.