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?

0

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I am manipulating myA seperately than myS; I need them both for different purposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.