Thread: vector accessing

  1. #1
    return 0;
    Join Date
    Jan 2005
    Location
    Netherlands
    Posts
    89

    vector accessing

    I was wondering if this is valid:

    Code:
    vector<int> v;
    v.push_back(5);
    v.push_back(100);
    v.push_back(22);
    
    function(&v[0]);
    The thing is, function() is expecting an int array. Is this the right way to do this, or does vector have some sort of function like std::string's c_str()?

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I was wondering if this is valid:
    ...and what prevents you from trying it? Are you afraid your computer will explode if you make a mistake?

  3. #3
    return 0;
    Join Date
    Jan 2005
    Location
    Netherlands
    Posts
    89
    Maybe I should've been more precise, but I have tried it and it works. I'm just not sure wether I'm supposed to do it like this and wether it's safe or not.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    That is the correct syntax to pass the contents of a vector to a function that takes only a C style array.

    Normally you would also pass the size of the vector to the function as well, since you cannot tell the size of an array from within a function it is passed to unless you have some other mechanism for knowing the size (like a global constant or something like that). So in this case, the function should not be accessing anything other than the first three elements in the array it receives.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    but I have tried it and it works. I'm just not sure wether I'm supposed to do it like this and wether it's safe or not.
    You might run into trouble if you used v.begin() instead of &v[0] because the type of v.begin() might be different. Also, my book says that for some reason the C++ standard did not make it clear whether the elements of a vector were required to be in contiguous memory. I don't really understand that since a vector dynamically creates an array to store the elements you insert in the vector, and a dynamically allocated array occupies contiguous memory. In any case, that was supposed to be corrected in the C++ standard so it would require that &v[i] == &v[0] + i. But, if you had an old compiler that implemented vectors in non-contiguous memory, then incrementing &v[0] might not work properly.
    Last edited by 7stud; 02-08-2006 at 05:08 PM.

Popular pages Recent additions subscribe to a feed