2012-09-27 79 views
1

我試圖定義一個動態數組,將數據從靜態數組複製到動態數組中,並將其複製回靜態數組。但似乎沒有正確複製數據。我做錯什麼了嗎?在動態指針數組和靜態數組之間複製數據

#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; 
} 

結果

[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

+0

好吧,我發現了錯誤。它應該是(i)memcpy(c,b,n * n * sizeof(* b));和(ii)p = b +(i * n); – twfx

回答

0

sizeof(*b)memcpy是你的問題,你只是得到一個雙倍的大小。您需要將malloc中使用的大小存儲在變量(或常量)中並使用它。

1

問題(或其中一人)可能是你正在嘗試

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

這應該不是是這樣的:

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

的原因是,你可能想存儲數據「按行」進入存儲器的指針,所以乘以i * n是至關重要的。如果您在查看時遇到問題,請設想j = 0,因此您希望行的第一個條目位於索引0,n,2 * n,...中。

1

按我的意見,你已經錯誤地分配內存, 你應該試試下面的代碼

#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]); 
     } 
    } 
}