0

I am trying to make a function that can return the size of an array that can be different data types. I believe the expression (sizeof(z)/sizeof(*z))) returns the memory allocated to z divided by the memory size of the data type. The following code is my attempt to overload the function and return the size of the array as an integer. When I run the expression in the main function it works, but when I try to pass the array to the function I do not get the correct values and not sure what I am doing wrong. 68 / 4 = 17 which is the correct size of the array.

(1) outputs sizeof(z) and sizeof(*z) in the size function

(2) expression in main function

(3) outputs sizeof(z) in the main function

(4) outputs sizeof(*z) in the main function

#include <iostream>

using namespace std;
//
int size(int *data){
  cout << sizeof(data) << ", " << sizeof(*data) << ", ";
  return((sizeof(data))/(sizeof(*data)));
}
int size(char *x){return(sizeof(x)/sizeof(*x));}
int size(float *x){return(sizeof(x)/sizeof(*x));}
int size(double *x){return(sizeof(x)/sizeof(*x));}
int size(short int *x){return(sizeof(x)/sizeof(*x));}
int size(long int *x){return(sizeof(x)/sizeof(*x));}

int main(){

  double x[9];
  int z[17];
  char k[29];

  cout << "(1) Size : " << size(z) << endl;
  cout << "(2) Size : " << (sizeof(z)/sizeof(*z)) << endl;
  cout << "(3) Size : " << sizeof(z) << endl;
  cout << "(4) Size : " << sizeof(*z) << endl;
  cout << "(5) Size : " << size(z) << endl;
  cout << "(6) Size : " << size(k) << endl;
  return 0;
}

Terminal Output:

(1) Size : 8, 4, 2
(2) Size : 17
(3) Size : 68
(4) Size : 4
(5) Size : 8, 4, 2
(6) Size : 8

2 Answers2

0

There's a common mistake:

char* a // is a pointer
char  b[] // is an array

when using:

char b[5]; // is an array of 5 bytes
sizeof(b); // 5
// but
char* a = b;
sizeof(a); // 8 (x64)

the last sizeof(a) is giving you the sizeof char * which is a pointer.

You can pass the name of an Array as a Pointer to the size() function, but in that function, the argument is treated as Pointer.

Evg
  • 25,259
  • 5
  • 41
  • 83
Terry Wu
  • 178
  • 9
0

An array decays to a pointer when you pass it to another function, so sizeof(arr) will give you the actual amount of memory allocated, only in the scope of the function in which arr was declared.

goodvibration
  • 5,980
  • 4
  • 28
  • 61