1

I am using an array of vectors. I have to count number of rows in the array. I am using the technique used for a 2D array. But it does not give desired output.

int main()
{    
    int i,p=7;
    vector<float> *mat=new vector<float>[p];
    int k=5;
    for(i=0;i<p;i++){
        mat[i].assign(k,0);
    }
    cout<<sizeof(mat)/sizeof(mat[0])<<endl;

return 0;
}

Why is this resulting in 0 ? Shouldn't the output be 7? How to calculate number of rows ?

12
  • 5
    First of all, sizeof(mat) give you the size of the pointer, not the size of whatever memory it point so. Secondly, sizeof(mat[0]) give you the size of the std::vector object itself, not the number of elements in the vector (that would be e.g. mat[0].length()). And why don't you use a vector of vectors (i.e. vector<vector<float>>) instead (or if k is a compile-time constant, a vector of arrays, as in vector<array<float, 5>>)? Commented May 28, 2018 at 9:33
  • Possible duplicate of Pointer array and sizeof confusion Commented May 28, 2018 at 9:35
  • @remi sizeof is a computed at compile time, you can't do mat[0].length() Commented May 28, 2018 at 9:40
  • @Tyker Ah, right. Will remove that comment, thanks. Commented May 28, 2018 at 9:41
  • @Tyker I guess it was .size() I meant. Wouldn't that work? Commented May 28, 2018 at 9:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.