2

Could someone tell me is there is a way to retain the correct size of the arrays when looking them up in the LOOKUP array? I have a felling it is impossible due to C losing the information as soon as you treat the array as an int pointer.

const int NUMBERS1[] = {1, 2, 3, 4, 5 };
const int NUMBERS2[] = {1, 2, 3, 4, 5 };
const int* LOOKUP[] = { NUMBERS1, NUMBERS2 };


int main()
{
  int correctSize = sizeof(NUMBERS1); // correctSize == 20
  int wrongSize = sizeof(LOOKUP[0]); // wrongSize == 4
}
oggmonster
  • 4,672
  • 10
  • 51
  • 73

3 Answers3

7

No, sizeof is correct. LOOKUP[0] is of type int* and sizeof(int*) is 4 on your system.

I have a feeling it is impossible due to C losing the information as soon as you treat the array as an int pointer.

That is correct. You have to keep track of the length.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
5

The main problem is that you've declared LOOKUP to be an array of pointers to int, not an array of arrays of int, so the type of LOOKUP[0] is going to be int *. The secondary problem is that, most of the time, array expressions will be converted to pointer expressions and the array size information will be lost.

If you need to know the size of an array in any context where the array expression has already been converted into a pointer expression, you need to store that size separately.

Here's one approach - use a struct to associate the array pointer with the array size:

#include <stdio.h>

int main(void)
{
  int NUMBERS1[] = {1, 2, 3, 4, 5};
  int NUMBERS2[] = {1, 2, 3, 4, 5, 6};
  int NUMBERS3[] = {1, 2, 3, 4, 5, 6, 7};

  struct arr_and_size {
    int *arrp;
    size_t size;
  };

  struct arr_and_size LOOKUP[] = {{NUMBERS1, sizeof NUMBERS1},
                                  {NUMBERS2, sizeof NUMBERS2},
                                  {NUMBERS3, sizeof NUMBERS3}};

  size_t i = 0;
  for (i = 0; i < sizeof LOOKUP / sizeof *LOOKUP; i++)
    printf("LOOKUP[%zu].arrp = %p, LOOKUP[%zu].size = %zu\n", 
      i, LOOKUP[i].arrp, i, LOOKUP[i].size);

  return 0;
}
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

LOOKUP is an array of pointers, not an array of arrays. The size of a pointer is 4 bytes on your system, so sizeof(LOOKUP[0]) will evaluate to 4.

qbert220
  • 11,220
  • 4
  • 31
  • 31