I'm working on a little code snippet and my c++ seems a bit rusty. How do i go about getting the length of an array? My eclipse is giving me weird values when it should be segfaulting, so I'm trying to figure out whats wrong. Thanks in advance.

edit: forgot to say what i meant by an int array.

int *x = new int[8];

Are you saying to use a different variable type?
Or are you saying to type cast it?

If its the first, I want to get the length of a pointer thats being passed.

Edit: Forgot to say, thanks for the help. Normally I'd use a vector like that, except in this case I'm being passed an in pointer.

Are you saying to use a different variable type?
Or are you saying to type cast it?

If its the first, I want to get the length of a pointer thats being passed.

Edit: Forgot to say, thanks for the help. Normally I'd use a vector like that, except in this case I'm being passed an in pointer.

I'm pretty sure it's impossible to get the length of an array from the address of the base pointer. You the programmer are responsible for keeping track of the length. That's why when you pass an array to a function, you generally pass the length as well. Regarding "length of a pointer", I assume you are referring to "number of elements in the array"? Regardless, I know of no way to get the 8 from x in your original example. Store 8 in a separate variable.

Yeah, I didn't think so either, but I just wanted to check. I think there might be a way if you know what your being passed and using sizeof(), but thats not what I was looking for. Thanks for your help.

You always have to pay attention when you create a vector of pointers, consider this:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int*> myvec(5);

    if( 5 > 3 )
    {
        int a = 35;
        myvec[0] = &a;
        cout << *myvec[0] << endl;
    }

    cout << *myvec[0] << endl; // not guaranteed to print 35 on the screen
	
    return 0;
}

When variable a goes out-of-scope, then the first pointer in vector myvec (myvec[0]) will point to some memory location which doesn't belong to your program anymore.

This question has already been answered. Start a new discussion instead.