简体   繁体   中英

Array Initialization from a struct

I was wondering if there was a way to initialize an array out of a variable from a struct. Say you have a struct like this-

struct Test{  
    int Number;  
};

And you wanted to initialize the int Number to become an array.
I've already tried this, and it doesn't work:

Test t1;  
t1.Number = new int[3];   
t1.Number[3] = 6;

I know ISO C++ forbids resizing arrays, but if there was a way to initialize the integer to be an array, that's not really resizing(isn't it?) Also, vectors don't work inside of structs. I get a " Vector does not name a type " error.

PS , I can't do this either:

struct Test{  
    int Number[5];  
};

Because at that time I don't know the size of the array I want.

vector works just fine in structs:

#include <vector>

struct Test {
    std::vector<int> Numbers;
};

I'm not sure what you're really trying to do but I think this comes close.

You can use a pointer to int -- ie,

struct Test{  
    int *Number;  
};

Then you can assign this at any future time to point to an array of your preferred size:

t.Number = new int[5];

But as other posters have already said, std::vector , with a small "v", works fine; be sure to #include <vector> so the compiler knows what you're talking about.

One trick to do this

struct Test {
  int Numbers[1];
};

when you initialize the struct, you need to use your own allocation function.

struct Test *NewTest(int sizeOfNumbers) {
  return (struct Test*)malloc(sizeof(struct Test) + sizeof(int)*(sizeOfNumbers - 1));
}

then, you will be able to access the numbers by using,

struct Test *test1 = NewTest(10);
test1->Numbers[0]...
test1->Numbers[1]...
test1->Numbers[9]...

The return value of new int[3] is an int* not an int . To make your code work you can do:

struct Test {  
    int* Number;  
};

int main() {
    Test t1;  
    t1.Number = new int[4]; // Note this should be 4 so that index 3 isn't out of bounds
    t1.Number[3] = 6;
    delete t1.Number;

    return 0;
}

However you should really use a std::vector rather than a static array. Vectors work just fine inside structs:

#include <vector>

struct Test {  
    std::vector<int> Number;  
};

int main() {
    Test t1;  
    t1.Number.resize(4);   
    t1.Number[3] = 6;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM