>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:
I guess this would be helpful,
/******for a static array********/
char inp[4];
for (n=0;inp[n];n++)
; //do nothing inside the loop
cout<<n; //n will display the number of elements in the array inp[]
/******for dynamic array********/
char *arr = new char [sizeof(char)];
for (n=0;arr[n];n++)
; //do nothing inside the loop
cout<<n; //n will display the number of elements in the array arr[]
>> I guess this would be helpful
No, not a bit. Your code is wrong.
>> for (n=0;inp[n];n++)
Assuming that n was defined somewhere, the test for imp[n] against 0 is dngerous because imp is uninitialized. There could be a null character straight away, or 5000 characters later. You're really risking an access violation with this loop.
>> char *arr = new char [sizeof(char)];
This alloctes memory for one char. sizeof(char) is guaranteed to return 1, everywhere, without fail. That's one of the few absolutes when it comes to type sizes in C++.
>> for (n=0;arr[n];n++)
You have the same problem here as the previous loop.
Yes, your idea is valid assuming there's some sentinel value at the end of the array to stop the loop on. With the original question that's difficult because any string object is valid in the general case. That's probably why you took it upon yourself to change the example to char so that you could use a null character as the sentinel.
The best solution is to avoid using arrays in the first place because they're unsafe and most people don't understand them well enough to avoid the pitfalls, as displayed by your flawed example. The std::vector class provides a good container that grows dynamically.
>> The easiest way to get the length of a dynamic array is this
Is it? Forget about the 'array' part and look closely at the 'dynamic' part. A dynamic array is not an array, it's a pointer to a block of memory that can be subscripted like an array:
So the sizeof trick just breaks silently when you use it on a dynamic array, or an array passed as a function parameter. Templates are a better solution because they complain when you pass a pointer and not an array:
The rule of thumb is that if you want the size of a dynamic array, you save it! If you want the size of an array parameter, you pass it! Anyone who doesn't know these rules or isn't comfortable with them would be better off using a smart container like std::vector or boost::array.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.