sachin11
sachin11

Reputation: 1167

C++ Array of struct initialization

I am not really used to coding in C++ and this probably is a simple issue that I am not able to get the correct syntax of.

What I am basically trying to achieve is that, from one method where I declare an array of a struct (size not specified), I call a method where I pass this array. The method should initialize the values of the array. I tried to get a simple code working but getting errors. The following piece of code gives me a compilation error. Can someone point out how to achieve this?

struct ABC
{
int a;
int b;
};

void test(ABC * a)
{
a[] = {{2,3},{4,5}};
}

int main() {
    ABC arr[2];
    test(arr);
}     

EDIT:
The following works, but I would like the initialization to work in one line.

struct ABC
{
int a;
int b;
};

void test(ABC *a)
{
a[0].a = 2;
a[0].b = 3;
a[1].a = 4;
a[1].b = 5;
}

int main() {
    ABC arr[2];
    test(arr);
}

Upvotes: 0

Views: 126

Answers (3)

Chiel
Chiel

Reputation: 6194

You could use a setup like this, making use of the C++ standard library. Compile it with the -std=c++11 flag to allow for the initialization I did in the push_back:

#include <vector>
#include <iostream>

struct ABC
{
    int a;
    int b;
};

void test(std::vector<ABC>& a)
{

    a.push_back({2,3});
    a.push_back({4,5});
}

int main()
{
    std::vector<ABC> arr;
    test(arr);

    // Test the outcome...
    std::cout << "The size is: " << arr.size() << std::endl;
    for (ABC& a : arr)
        std::cout << "Element (" << a.a << "," << a.b << ")" << std::endl;

    return 0;
}

Upvotes: 2

SunKnight0
SunKnight0

Reputation: 3351

You have to first find out the actual size of the array and then iterate to initialize it.

Will not work, see below

void test(ABC* a) {        
    int value=2;
    for (int i=0;i++;i<sizeof(a)/sizeof(ABC)) {
        a[i].a=value;
        a[i].b=value+1;
        value+=2; } }

I am not 100% sure the sizeof(a) will work in giving you the size of the array. If that does not work you will have to pass the size of the array as a parameter:

void test(ABC* a, int elements) {        
    int value=2;
    for (int i=0;i++;i<elements) {
        a[i].a=value;
        a[i].b=value+1;
        value+=2; } }

int main() {
    ABC arr[2];
    test(arr,2); }

Upvotes: -1

hlscalon
hlscalon

Reputation: 7552

Initialize each struct accessing its index in a array.

void test(ABC * a)
{
    a[0] = {2,3};
    a[1] = {4,5};
    ...

This way {{2,3},{4,5}}; will work on initialization, i.e

ABC arr[2] = {
    {2,3},
    {4,5}
};

Upvotes: 0

Related Questions