Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a pointor variable to complete array (not the first element example: int *ptr = &arr, not int *ptr = arr)

I wanted to use the fact that &arr points to the complete arr and not just the first element, to calculate array length like this

int size = *(&arr + 1) - arr ;

Now this will work in main function but I want to calculate the size within a function in which array is not defined and takes arr as parameter.

As arr decays into a pointer when passed into a function. sizeof(arr)/sizeof(arr[0]) method does not work as it means

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sizeof(int*) / sizeof(int) 
// i.e. 4/4 = 1.

I wanted to use &arr method inside a function but that does not work too for some reason… which is why I wanted to pass &arr as a parameter inside the function. I tried simply pass it by writing &arr as a parameter, but I am confused what is the data type of &arr as it says expected

expected 'int *' but argument is of type 'int (*)[4]'

which is good as I am passing int(*)[4] only but how to specify this inside function parameter.

>Solution :

… to calculate the size within a function in which array is not defined and takes arr as parameter.

In C, when variable length arrays are available:

// The array is not defined here.
void bar(size_t n, int (*arg)[n]) {
  // Size of the array from main() is calculated here.
  size_t size = sizeof *arg / sizeof *arg[0];
  printf("%p %zu\n", (void*) arg, size);
}

int main(void) {
  // Array defined here.
  int arr[42];
  size_t sz = sizeof arr / sizeof arr[0];
  bar(sz, &arr);
  return 0;
}

Output

0xffffcbe0 42
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading