Click here to Skip to main content
16,015,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my code:
C++
size_int Length() {
        size_int len = 0;
        for (int i = 0; i < IntInf; i++) {
            try {
                char temp = data[i];
                len++;
            } catch (...) {
                break;
            }
        }
        return len;
    }

What i want to make it do is go through all the elements of data (which is a char array) and IntInf is the maximum number possible for integers (2 billion something) and when the data array only has say 3 chars lets say "H", "E" and "Y" ("HEY"), then i want it to count up to three then because it tries to access data[3] (4th element) and it doesn't exist... It should throw an error like other languages no? Well appearantly not, it just keeps going and gives me back the value for IntInf, WHY DOESN'T IT ERROR WHEN YOU NEED IT TO. I know this solution is wierd and inefficient but it's the only way i know to get the length of a char array as they have different lengths of chars so you can't just do (sizeof(data)/sizeof(data[0]). Please help this is driving me insane.

What I have tried:

I tried making a char vector and adding all the elements, again using the InfInf loop but because the try catch doesn't work like i want it to it didn't simply to go catch... It crashed the entire program.

I know somebody might mention the strlen thingy, i tried it. It gives me some number with 8 or 80 billion. WHAT THE F**K?
Posted
Updated 3-Dec-21 8:04am
v3
Comments
Richard MacCutchan 3-Dec-21 8:16am    
Because C (and C++) does not do any bounds checking of simple arrays. You need to pass the number of elements to your function, or use a C++ type with iterators. And strlen will only give a valid result for a properly structured C-style string, i.e. one with a terminating null character

Your try/catch block doesn't do anything because C/C++ does not do bounds checking of array indexers.

The real question is why you're using a straight up array instead of a vector, which does do bounds checking internally.
 
Share this answer
 
Comments
CPallini 3-Dec-21 8:42am    
Even with vector: 'Accessing a nonexistent element through this operator is undefined behavior'. You have to use at() if you need an exception.
See
https://en.cppreference.com/w/cpp/container/vector/operator_at
Dave Kreskowiak 3-Dec-21 9:53am    
Yes, but it's a lot easier to check the indexer against the vector.size than it is to wait for an exception that will never come.
CPallini 3-Dec-21 10:45am    
if you use the at method then the exception is magically generated.
Dave Kreskowiak 3-Dec-21 12:40pm    
Yeah, it does, but using an Exception in the normal course of an operation is bad practice. I'd rather compare against a known limit, like size, or scan the array for a terminator, like 0x00, to get the length.
Member 14769677 3-Dec-21 8:42am    
Well i wrote a big class with the idea of using an array. The code is 1200 lines long.
 
Share this answer
 
If you write non-trivial code, you should really watch out to write clean code, and use container classes and range-for[^] instead of C arrays and index based loops.

E. g. your function could be rewritten in a much safer way like this:
C++
size_int Length() {
        size_int len = 0;
        for (auto temp : data) {
            try {
                len++;
            } catch (...) {
                break;
            }
        }
        return len;
    }
This obviates the need for the try block too, unless the type size_int might throw upon calling the increment operator.

Note that this even works with a C array, unless you allocated it on the heap.

If all you want is the length of the array, you could also use std::begin() and std::end() to determine the range. Here are examples for the last two suggestions:
C++
#include <iostream>
struct test {
    int data [4];
    size_t len1() {
        size_t l = 0;
        for (auto tmp : data)
            ++l;
        return l;
    }
    size_t len2() {
        return std::end(data) - std::begin(data);
    }
};
int main()
{
    test t;
    std::cout << t.len1() << "\n";
    std::cout << t.len2() << "\n";
    return 0;
}
This will print 4, twice.

Of course, if you allocated this array dynamically, using new[] or malloc, than the only way to obtain the array size is saving this information at the time when you allocate the array! But if that is what you do, you really should use std::vector instead!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900