Initialize C++ struct that contains a fixed size array

Viewed 110

Suppose I have a POD C struct as so:

struct Example {
    int x;
    int y[10];
    int yLen;
}

With the following code, the program doesn't compile:

Example test() {
    int y[10];
    int yLen = 0;

    auto len = this->getSomethingLength();
    for (int i = 0; i < len; i++) {
        y[yLen++] = this->getSomething(i);
    }

    return Example{ 0, y, yLen };
}

However, doing return {0, {}, 0}; does seem to compile. Problem is, I can't know the size of y until doing some sort of logic ahead of time. Initializing int y[10]{} in test doesn't seem to make a difference. I know this seems like a pretty simple question, but I can't seem to find anything that works.

2 Answers

Declare the structure as a whole instead of its parts and then initialize it:

Example test() {
    Example result;

    auto len = this->getSomethingLength();
    for (result.yLen = 0; result.yLen < len; result.yLen++) {
        result.y[result.yLen] = this->getSomething(result.yLen);
    }

    return result;
}

Declaring y as an int* and allocating memory with new, when the size is known, would be an even better solution.

Declare constructor in Example:

struct Example {
    int x;
    int y[10];
    int yLen;
    Example(int xNew, int *yNew, int yLenNew)
    {
        x = xNew;
        yLen = yLenNew;
        for (int i = 0; i < yLenNew; i++)
        {
            y[i] = yNew[i];
        }
    }
};

And use it like this:

Example test() {
    int y[10];
    int yLen = 0;

    auto len = this->getSomethingLength();
    for (int i = 0; i < len; i++) {
        y[yLen++] = this->getSomething(i);
    }

    return Example( 0, y, yLen );
}
Related