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

Time:04-08

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

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?

CodePudding user response:

... 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:

#include <stdio.h>
#include <stdint.h>

// The array is not defined here.
//                            v
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);
  // Akin to OP's calculation method
  ptrdiff_t diff = *(arg   1) - *arg;
  printf("%p %td\n", (void*) arg, diff);
  printf("%p %zu\n", (void*) arg, n);
}

int main(void) {
  // Array defined here.
  int arr[42];
  int size = *(&arr   1) - arr ;
  printf("Main: %d\n", size);
  size_t sz = sizeof arr / sizeof arr[0];
  bar(sz, &arr);
  return 0;
}

Output

Main: 42
0xffffcb40 42
0xffffcb40 42
0xffffcb40 42

CodePudding user response:

Syntax to pass reference to array in C is:

template <typename T, std::size_t N>
std::size_t size(const T (&a)[N])
{
    return N;
}

for C, you don't have template to deduce size, so type/size would be hard coded:

void foo(const int (*arr)[42])
{
    // ...
}
  •  Tags:  
  • c
  • Related