1

I tried to define a dynamic array, copy the data from a static array into the dynamic array, and copy back to a static array. But it seems that the data is not copied properly. Did I do something wrong?

    #include <stdio.h>

int main(){
    int n = 2;
    double a[2][2];
    double c[2][2];
    a[0][0] = 0.0;
    a[0][1] = 0.1;
    a[1][0] = 1.0;
    a[1][1] = 1.1;

    double* b = NULL;
    double* p = NULL;
    int i,j;

    b = (double*) malloc(n*n*sizeof(double));

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            p = b+i;
            *(p+j) = a[i][j];
        }
    }

    memcpy(c, b, sizeof(*b));    

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            p = b+i;
            fprintf(stderr, "[%d][%d] = %.1f, c[%d][%d] = %.1f \n", i, j, *(p+j), i, j, c[i][j]);              
        }
    }

    free(b);
    b = NULL;

    return 0;
}

result

[0][0] = 0.0, c[0][0] = 0.0

[0][1] = 1.0, c[0][1] = 0.0

[1][0] = 1.0, c[1][0] = 0.0

[1][1] = 1.1, c[1][1] = 0.0

twfx
  • 1,664
  • 9
  • 29
  • 56
  • ok, i spot the error. It should be (i) memcpy(c, b, n*n*sizeof(*b)); and (ii) p = b+(i*n); – twfx Sep 27 '12 at 09:06

3 Answers3

1

The problem (or one of them) might be that you are trying

 p = b+i;
*(p+j) = a[i][j];

which should instead be something like this:

*(p+i*n+j) = a[i][j];

The reason is, that you probably want to store the data "by row" into the memory at the pointer, so it is critical to multiply i*n. If you have trouble visualizing it, imagine j=0, so you want the first entries of the rows to be in the indices 0, n, 2*n,... .

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
1

As per my opinion you have wrongly allocated memory, You should try below code

#include <stdio.h>

int main()
{
    int n = 2;
    double a[2][2];
    double c[2][2];
    a[0][0] = 0.0;
    a[0][1] = 0.1;
    a[1][0] = 1.0;
    a[1][1] = 1.1;

    double** b = NULL;
    int i,j;

    b = (double**) malloc(n * sizeof(double*));
    for(i = 0; i < n; i++)
        b[i] = (double *)malloc(n * sizeof(double));

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            b[i][j] = a[i][j];
        }
    }

    memcpy(c, b, (n*n*sizeof(double)));

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            printf("b[%d][%d] = %lf, c[%d][%d] = %lf, a = %lf\n", i, j, b[i][j], i, j, c[i][j], a[i][j]);
        }
    }
}
Chirag Desai
  • 1,249
  • 1
  • 10
  • 22
0

sizeof(*b) in the memcpy is your problem, you just get the size of one double. You need to store the size used in malloc in a variable (or constant) and use that.

cdarke
  • 42,728
  • 8
  • 80
  • 84