2

The code:

int i;
struct st
{
    int m;
}st_t[2];

void foo()
{
    i = 4;
    st_t[2] = 
    {
       {10},{20}
    };  // it's wrong !!!!  but I don't know how to do.     
}
int main()
{
   foo();
   cout<<i<<endl;          // will output 4;
   cout<<st_t[0].m<<endl;  // this should output 10
   cout<<st_t[1].m<<endl;  // this should output 20

   return 0;
}

Is it possible to define a struct array in a function? If it is, then how to do this? Thanks in advance.

PS:
Sorry my English is not good. I am making a Tetris game, it have a Shape class, I declared a shape struct array in Shape.h, then I assign to the struct array in Shape constructor function in Shape.cpp. Is it right? or how to assign to the struct array so I can use it in another function?

4

4 回答 4

2

You can initialize an array in the place where it's defined. I.e. either move the definition into the function, or move the initialization out of the function:

struct st 
{ 
    int m; 
} 
st_t[2] = {{10},{20}};
于 2012-09-11T13:35:36.140 回答
0

If you want to define an array in the function (as your question title and text implies), then add the type specifier st to the definition:

st st_t[2] = 
{
   {10},{20}
};

However, this will be a separate array to the global one, and so the output from main() won't match what your comments say should happen. If you actually want to assign to the global array, then:

st_t[0].m = 10;
st_t[1].m = 20;

or, in C++11, you can use similar syntax to your example if you replace the plain array with std::array:

std::array<st, 2> st_t;

void foo() {
    // Note the extra braces - std::array is an aggregate containing an array
    st_t = 
    {{
        {10},{20}
    }};
}
于 2012-09-11T13:39:14.270 回答
0

If you only want the variable at function scope then

void foo() {
    struct {
        int m;
    } st_t = { {10}, {20} };
    // do something
}
于 2012-09-11T13:58:36.020 回答
0

Instead of the direct assignment of values, you can initialize a temporary variable and copy this variable to your global variable:

Delete:

 ...
 st_t[2] =  {
      {10},{20}
 };
 ...

and add:

 ...
 st tmp[2] = { {10}, {20} };  

 memcpy(st_t, tmp, sizeof st_t);
 ...

Addendum:

If it doesn't work for you, there might be another error in your code. From your example:

#include <iostream>
#include <memory.h>
using namespace std;

 int i;
 struct st { int m; } st_t[2];

 void foo()
{
 i = 4;
 st tmp[2] = { {10}, {20} }; 
 memcpy(st_t, tmp, sizeof st_t); // use: const_addr instead of &const_addr
}

 int main()
{
 foo();
 cout << i << endl;          // will output 4;
 cout << st_t[0].m << endl;  // this should output 10
 cout << st_t[1].m << endl;  // this should output 20
 return 0;
}

all works fine as expected.

于 2012-09-11T14:06:38.147 回答