lundi 4 décembre 2017

C++ sizeof on string array not returning expected results when passed to a function [duplicate]

This question already has an answer here:

Trying to find the size of an array dynamically. Getting the size while in main() works fine but doesn't when i pass it to the GetSize function.

#include <iostream>
#include <string>

using namespace std;

string GetSize(string array[]);

int main()
{
  string array[] = {"A", "B", "C", "D", "E"};
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Total Size: " << sizeof(array) << endl;
  cout << "Single Element Size: " << sizeof(array[0]) << endl;

  // Pass the array as an argument to GetSize()
  GetSize(array);
}

string GetSize(string array[])
{
  // Get size of the array
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Size of array is: " << sizeof(array) << endl;
  cout << "Size of 1st element is: " << sizeof(array[0]);    
}

Output

// Total Size: 160
// Single Element Size: 32
// Size of array is: 8
// Size of 1st element is: 32

I have no clue why the discrepancy between the Total Size and the Size of array.

Repl Sandbox: http://ift.tt/2ihZZHl

Aucun commentaire:

Enregistrer un commentaire