1

I can declare and initialize an array like this:

int dest_linesize[4] = {  4 , 0 , 0 , 0 };

I can always assign values to the individual members of the array by:

dest_linesize[0] = 5;

But can I assign multiple values with something like this?

dest_linesize = {  4 , 3 , 1 , 0 };

2 Answers 2

2

With C-style array? No, they are not reassignable.

With C++ std::array? Sure

#include <array>
int main()
{
    std::array<int, 4> dest_linesize = {4 , 0 , 0 , 0 };
    dest_linesize[0] = 5;
    for(int n:dest_linesize) {
        std::cout << n << " ";
    }
    std::cout << "\n";

    dest_linesize = {  4 , 3 , 1 , 0 };
    for(int n:dest_linesize) {
        std::cout << n << " ";
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

if i have to pass a c style array to a function how can i pass the std::array ?
@shomit If you can't change that function, dest_linesize.data() will extract the underlying array.
2

can i do something like this instead where i can assign multiple values.

dest_linesize = {  4 , 3 , 1 , 0 };

No, you cannot. Arrays are not assignable.

One solution is to wrap the array inside a class. Classes are assignable. There is a template for such wrapper in the standard library. It is called std::array. Example:

std::array dest_linesize = {  4 , 0 , 0 , 0 };
dest_linesize = {  4 , 3 , 1 , 0 }

Comments

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.