0

I want to write a function that returns the size of a quadratic matrix; i.e. for a 5x5 matrix as below in my code the function "get_table_size" should return 5. However, in the example below, "get_table_size" returns 8; but when I use the macro "SIZE", that does exaclty the same thing as the function, it returns the correct number, namely 5.

Could you please tell me what I am doing wrong?

#include <stdio.h>
#include <stdlib.h>


#define SIZE(table) ((int) (sizeof (table) / sizeof (table)[0]))


int get_table_size(char* table)
{
   return (sizeof(table) / sizeof(table)[0]);
}

int main()
{

  char table[5][5] =
  {
    {'A', 'B', 'C', 'D', 'E'},
    {'F', 'G', 'H', 'I', 'J'},
    {'K', 'L', 'M', 'N', 'O'},
    {'P', 'Q', 'R', 'S', 'T'},
    {'U', 'V', 'W', 'X', 'Y'}
  };

    printf("\n");
    printf("%d\n", get_tableu_size(table));   // does not work
    printf("%d\n", SIZE(table));        //does work

  return 0;
}
3nondatur
  • 353
  • 2
  • 9
  • 1
    `sizeof(table)` is the size of the pointer argument. There is no way to get the size of the data being pointed to, from the pointer alone (unless you use sentinel values). Your function use is wrong anyway - it assumes a 1-D array was passed but you gave it a 2-D array. *And* the syntax `sizeof(table)[0]` is wrong. – Weather Vane Apr 11 '23 at 16:31
  • 1
    After fixing the typo, [heed the warnings](https://godbolt.org/z/cf4zod3MT) – yano Apr 11 '23 at 16:32
  • 1
    `char* c = /* something */; sizeof(c);` will return the size of the pointer, _not_ the length of some underlying array (which is really just a sequential set of pointers). `char d[] = /* something */; sizeof(d);` will return the length of the array. So your `sizeof(table) / sizeof(table[0])` (note the fixed typo) will not work for a pointer. The solution is to keep track of these array lengths, and pass them accordingly (either as a `struct` or another function argument). – Rogue Apr 11 '23 at 16:32
  • 1
    The function `get_table_size` does not know the size of the array ! – Yves Daoust Apr 11 '23 at 16:41
  • 1
    @WeatherVane The syntax `sizeof(table)[0]` works fine but just looks wrong! At least it doesn't look as wrong as `sizeof(0)[table]` which of course also works fine. – Ian Abbott Apr 11 '23 at 16:45
  • 1
    @IanAbbott you are right it's not wrong, I geddit now. It's like doing say `int i = (table)[0];` – Weather Vane Apr 11 '23 at 16:50

0 Answers0