number of elements of an array of strings

Jun 5, 2008 at 9:11pm
is there a function that returns the number of elements of an array of strings?? if not, how do i get the number of elements??, here is an example:
i define an array of strings:

string itembuy[]={"axe","potion"};

obviously it has 2 elements, but lets say i can erase or add elements , and im constantly printing the content of this array with a for loop, so i need to know the number of elements to put in the testing statement of the for so i can print the whole content without getting out of the bounds of the array...

for(int i=0;i<??????;i++){
cout<<itembuy[i]<<endl;
}

i<??????, help please..
Jun 5, 2008 at 9:31pm
There is a trick you can use.

It works only under the following conditions:

1. You are using the actual array identifier, and not a pointer or argument or any other variable reference to the array.

2. You know either
2.a. the type of the array's elements
2.b. there is at least one element in the array.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
using namespace std;

string a[] = { "one", "two", "three" };  // 2.b
string b[] = {};                         // 2.a

int main()
  {
  int size_of_a = sizeof( a ) / sizeof( a[ 0 ] );
  int size_of_b = sizeof( b ) / sizeof( string );

  void print( const string&, const string*, int );

  print( "a[]", a, size_of_a );
  print( "b[]", b, size_of_b );
  }

void print( const string& name, const string a[], int size )
  {
  cout << "The array " << name << " contains " << size << " elements:\n";
  for (int i = 0; i < size; i++)
    cout << i << ": " << a[ i ] << endl;
  cout << endl;
  }


Hope this helps.

[edit] fixed typo [edit2] unfixed non-typo
Last edited on Jun 5, 2008 at 9:51pm
Jun 6, 2008 at 10:06am
Douas:
Is every string in an array using the same number of memory?

So if A = {"a", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
sizeof(A[0]) == sizeof(A[1]) ?
Jun 6, 2008 at 11:18am
Yes. A string is an object that looks something like (highly simplified):
1
2
3
4
5
6
7
8
9
10
class string
  {
  private:
    char*    f_data;
    unsigned f_length;

  public:
    string(): f_data(0), f_length(0) { }
    ...
  };

Objects always have the same size. As do pointers, ints, floats, etc. So an array of anything will always have same-size elements.

The data itself may use differing amounts of memory, but the data is not stored directly in the array. Rather it is stored on the heap (where stuff you get from new() is kept) or in the read-only data segment (where stuff like "Hello world!" is kept).

:-)
Topic archived. No new replies allowed.