get length of a dynamic array
Can't seem to figure this out.
string *array;
void addNodes(string names[])
{
array = names;
//how many elements in the array???
}
Phaelax
Practically a Posting Shark
858 posts since Mar 2004
Reputation Points: 92
Solved Threads: 51
>Can't seem to figure this out.
You're not the only one. There isn't a portable way to get the size of a dynamically allocated array. You need to pass the size to your function:
void addNodes(string names[], size_t size)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Try it with a dynamic array and find out you are wrong.
You are being helpfully corrected, you are the one starting to get out of line.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
I get 4 for the sizeof(string), hmmm?
I 'd say vectorize!
vegaseat
DaniWeb's Hypocrite
5,976 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,416
Can't seem to figure this out.
string *array;
void addNodes(string names[])
{
array = names;
//how many elements in the array???
}
std::string has a functionsize() that will tell the current size.
void addNodes(string names[])
{
cout << "size of array is " << names.size() << "\n";
}
>> array = names;
That does not work because you variablenames is a c++ class, not a pointer. If you want the pointer, then use c_str()
const char* array = names.c_str();
Ancient Dragon
Retired & Loving It
30,040 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341
std::string has a function size() that will tell the current size.
void addNodes(string names[])
{
cout << "size of array is " << names.size() << "\n";
}
Hmm...you are forgetting thatnames is an array of strings and not a std::string or a vector. So you can't apply the size( ) function to it, it is applicable to C++ containers, not array of containers. The only way to do this thing correctly is to do it like specified by Miss Narue in the second post.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
Hmm...you are forgetting that names is an array of strings and not a std::string or a vector. So you can't apply the size( ) function to it, it is applicable to C++ containers, not array of containers. The only way to do this thing correctly is to do it like specified by Miss Narue in the second post.
Yes you are correct -- my mistake. Best thing for the op to do is use a vector instead of an array. I was wondering at the time how Narue could possibly make such a mistake -- turns out she didn't.
Ancient Dragon
Retired & Loving It
30,040 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341