469,924 Members | 1,405 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,924 developers. It's quick & easy.

How to initialize a 2D static array?

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[i][j] = 18*90;
}
tmp = 1;
}

Mar 10 '07 #1
1 4004
"Vol" <vo********@gmail.comwrites:
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[i][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".)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 10 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by Kyle | last post: by
2 posts views Thread by slack_justyb | last post: by
5 posts views Thread by Jim Langston | last post: by
10 posts views Thread by Yang Lee | last post: by
15 posts views Thread by Geoff Cox | last post: by
18 posts views Thread by toton | last post: by
15 posts views Thread by thinktwice | last post: by
8 posts views Thread by aaragon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.