开发者

C: Problem with initializing array values to zero

开发者 https://www.devze.com 2023-04-04 22:06 出处:网络
I\'m trying to construct the following 14*14 array i C: [I 0; 0 -I], that is a 7*7 identity matrix upper left, minus the identity lower right and zeros otherwise.

I'm trying to construct the following 14*14 array i C: [I 0; 0 -I], that is a 7*7 identity matrix upper left, minus the identity lower right and zeros otherwise.

This is the method:

#define DIM 7

 double S[2*DIM][2*DIM];

 for(i = 0; i < DIM; i++){
     for(j = 0; j < DIM; j++){
         if(i == j){
             S[i][j] = 1.0;
             S[i+7][j+7] = -1.0;
         }
         else{
             S[i][j] = 0.0;
         }
     } 
 } 

开发者_开发问答This works fine for all the diagonal elements; however, some elements of the array get initialized to crazy values; for example, 13,6 gets initialized to

68111186113812079535019899599437200576833320031036694798491976301968333351950125611739840800974137748034248687763243996679617222196278187875968953700681881752083957666277350377710107236511681624408064.000000

This seems to be happening consistently (at least thrice) to entries 11,13, 12,9, 12,10, 13,12 and 13,6.

Can anybody tell me what's at play here or provide an alternative solution?

Cheers!

EDIT: The weird entries aren't consistent.

EDIT2: Typo: 13,12, not 13,15


Your loop only covers the upper left quadrant, so the off-diagonal elements in the other quadrants are not initialized and contain garbage. Your loop should go up to 2*DIM for each dimension, so that the off-diagonal elements are zeroed, and then your conditional for the diagonal elements should just be a little more complex to decide which value to set the diagonal element to.

Note that [13, 15] is entirely outside of this array!


You can initialize the whole array with zeros, then set only the diagonal

double S[2*DIM][2*DIM] = {0};
for (i = 0; i < DIM; i++) {
    s[i][i] = 1;
    s[i + DIM][i + DIM] = -1;
}


You are never writing to s[i][j] for i != j and i >= DIM or j >= DIM. If your array has automatic storage (is "local") it contains arbitrary init values.


I would say most of the elements that are outside 7x7 will not be initialized at all unless i == j (diagonal elements).

What do you want to initialize them to?


That's because your not initializing those elements. Here is some better code:

#define DIM 14

double S[DIM][DIM];

for (i = 0; i < DIM; i++) {
    for (j = 0; j < DIM; j++) {
        if (i == j) {
            if (i < 7) {
                S[i][j] = 1.0;
            } else {
                S[i][j] = -1.0;
            }
        } else {
            S[i][j] = 0.0;
        }
    } 
}


You never initialize values with an i or j between DIM + 1 and 2*DIM. So when you look at a value stored in one of those positions, you see whatever was there before that space was accessed by your matrix.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号