How to initialize a 2D static array?

V

Vol

Hi, Group,

I want to initialize a 2D static array in function 'foo ()', where
'foo' is called by another function a lot of times.
I list my implementation below but I think there are better
solutions , thanks

void foo()
{
int i, j;
static int dis_sum[100][100] = {18*90};
static int tmp = 0;

if (tmp == 0)
{
for(i = 0; i < 100; i++)
for(j = 1; j < 100; j++)
dis_sum[j] = 18*90;
}
tmp = 1;
}
 
K

Keith Thompson

Vol said:
I want to initialize a 2D static array in function 'foo ()', where
'foo' is called by another function a lot of times.
I list my implementation below but I think there are better
solutions , thanks

void foo()
{
int i, j;
static int dis_sum[100][100] = {18*90};

This initializes only the first element to 18*90; the others will be
initialized to 0. Since you're going to execute the loop before using
it, you don't need to bother initializing it when it's declared.
(Since it's static, it will be implicitly initialized to all zeros.)
static int tmp = 0;

"tmp" is a lousy name; call it something like "dis_sum_initilaized".
if (tmp == 0)
{
for(i = 0; i < 100; i++)
for(j = 1; j < 100; j++)
dis_sum[j] = 18*90;
}
tmp = 1;
}


100 is a "magic number"; if you later change the size of the array,
you'll have to change the values in several places in your code. Use
declared constants, most likely macros. Likewise for 18*90.

Apart from that, it looks like a reasonable way to initialize a static
object when the initial value is too complex for an actual
initializer. (It would be nice if there were a syntax for "initialize
all elements to 18*90".)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top