2

I am trying to initialize two copies of the same two-dimensional arrays in C. However, only one stores the correct data:

    //convert 1D array to 2D array
double** myA = malloc(n*sizeof(double*));
for (j=0;j<n;j++)
    myA[j]=&a[j*n];

double** myS = (double **) malloc(n*sizeof(double*));
for (i=0; i<n; i++)
    for (j=0; j<n; j++){
        myS[i] = (double *) malloc(n*sizeof(double));
        myS[i][j] = myA[i][j];
    }

printf("A:\n");
print_matrix(myA,n);
printf("S:\n");
print_matrix(myS,n);

I want to initialize two copies of A. One as myA and the other as myS. However, here is my output:

A:
0.000000 1.000000 2.000000 3.000000 4.000000 
1.000000 1.414214 2.236068 3.162278 4.123106 
2.000000 2.236068 2.828427 3.605551 4.472136 
3.000000 3.162278 3.605551 4.242641 5.000000 
4.000000 4.123106 4.472136 5.000000 5.656854 

S:
-0.000000 -0.000000 -0.000000 -0.000000 4.000000 
-0.000000 -0.000000 -0.000000 -0.000000 4.123106 
-0.000000 -0.000000 -0.000000 -0.000000 4.472136 
-0.000000 -0.000000 -0.000000 -0.000000 5.000000 
-0.000000 -0.000000 -0.000000 -0.000000 5.656854 

Why are all the columns but the last -0.000000?

Eric Baldwin
  • 3,341
  • 10
  • 31
  • 71

1 Answers1

3

You're overwriting each row buffer N-1 times (and leaking memory like a sieve leaks water in the process).

Change this:

for (i=0; i<n; i++)
    for (j=0; j<n; j++){
        myS[i] = (double *) malloc(n*sizeof(double));
        myS[i][j] = myA[i][j];
    }

To this:

for (i=0; i<n; i++)
{
    myS[i] = malloc(n*sizeof(double));
    for (j=0; j<n; j++)
        myS[i][j] = a[i*n+j];
}

Note two things in the above code:

  1. Don't cast malloc.
  2. The myA temp array is not needed. You can do the math with the index yourself. Throw that entire thing out.
Community
  • 1
  • 1
WhozCraig
  • 65,258
  • 11
  • 75
  • 141