Using sizeof() within a function

I can get the sizeof() function to work for my array airports[] within the main(), it comes up with 4 (the correct answer).

However when trying to use the exact same code within my DisplayAirports() function the answer it comes up with is 32? Confused?

int main()
{
Airport * airports = new Airport[4];
airports[0].Name = "Heathrow";
airports[0].Acronym = "LHR";
airports[0].Country = "England";

airports[1].Name = "Paris";
airports[1].Acronym = "PR";
airports[1].Country = "France";

airports[2].Name = "Madrid";
airports[2].Acronym = "MAD";
airports[2].Country = "Spain";

airports[3].Name = "Vegas";
airports[3].Acronym = "LVS";
airports[3].Country = "America";

int size;
size = sizeof ( airports );
cout << size;

keep_window_open();
return 0;
} // THIS WORKS AND DISPLAYS THE VALUE 4


void DisplayAirports(string n)
{
int i;
int size;

size = sizeof (n);
cout << size;
} // THIS DOESNT AND DISPLAYS THE VALUE 32. I'M CONFUSED HERE!

(Please ignore the lack of indentation as this was quickly copied. Also we have a predefined header which eliminated the need for much of the extra syntax used in c++).
try n.size(); with strings
Sorry, what do you mean by that? Can you be a little more specific aka how i would actually implement that code?
instead of size = sizeof (n);
try, just try size=n.size();
Last edited on
This returns the value 8 because it is calculating the size of the string passed, not the array which that string is trying to represent.
Last edited on
OK here is my conclusion ... c++ is a crazy language! No I'm joking. Ok this code works within the main function ()
1
2
3
4
5
6
7
for( int i = 0; i < 4; i++)
	{
	cout << "Name   : " << airports[i].Name << endl; 
	cout << "Acronym: " << airports[i].Acronym << endl;
	cout << "Country: " << airports[i].Country << endl; 
	cout << endl;
	}


however when i put it into the function DisplayAirports() it comes up with an error message?
Topic archived. No new replies allowed.