-
Why does this work?
Code:
// Phone list
#include <iostream>
#include <string>
using namespace std;
string getSearchStr();
void getEntry(string, string *, int);
int main()
{
string phoneList[] = { "Becky Warren, 678-1223", "Joe Looney, 586-0097",
"Geri Palmer, 223-8787", "Lynn Presnell, 887-1212",
"Holly Gaddis, 223-8878", "Sam Wiggins, 486-0998",
"Bob Kain, 586-8712", "Tim Haynes, 586-7676",
"Warren Gaddis, 223-9037","Jean James, 678-4939",
"Ron Palmer, 486-2783"
};
getEntry(getSearchStr(), phoneList, sizeof(phoneList) / sizeof(string));
cout << "Press enter to continue. . .";
cin.ignore();
cin.get();
return 0;
}
string getSearchStr()
{
string name;
cout << "Enter search criteria: ";
cin >> name;
return name;
}
void getEntry(string name, string * list, int size)
{
bool match = false;
for (int i = 0; i < size; i++)
{
if (list[i].find(name, 0) != string::npos)
{
match = true;
cout << list[i] << "\n";
}
}
if (!match)
cout << "Did not find a matching name.\n";
}
The question is why does sizeof(phoneList) / sizeof(string) return the right number of elements in the phoneList array? Each string is a different length so how does sizeof(string) get the right length?? I know how it works with ints and doubles and other built-in data types so I figured I'd try it here and it works. Just...how?
-
Well a string is a fixed sized object, the variable part of the object (ie the string itself) is typically stored in allocated memory.
-
Ok
Ah I was thinking that. :cool: