2017-03-10 96 views
1

我在分配內存後得到了關於這個int數組初始化的小問題。我得到了以下錯誤:int malloc初始化後的數組

"Line 7 Error: expected expression before '{' token"

這是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int i; 
    int *x=malloc(3*sizeof(int)); //allocation 
    *x={1,2,3}; //(Line 7) trying to initialize. Also tried with x[]={1,2,3}. 
    for(i=0;i<3;i++) 
    { 
     printf("%d ",x[i]); 
    } 
    return 0; 
} 

有沒有其他辦法,我做的內存分配後,初始化我的數組?

回答

0

首先,我們必須明白,數組的內存分配在堆內存區域。因此我們可以通過以下方法進行初始化。

  • 使用memcpy函數
  • 指針運算

上面兩個方法保留通過malloc函數的內存分配。 但由於先前分配的堆內存,通過(int []){1,2,3}進行分配將導致內存浪費

int* x = (int*) malloc(3 * sizeof(int)); 
printf("memory location x : %p\n",x); 

// 1. using memcpy function 
memcpy(x, (int []) {1,2,3}, 3 * sizeof(int)); 
printf("memory location x : %p\n",x); 


// 2. pointer arithmetic 
*(x + 0) = 1; 
*(x + 1) = 2; 
*(x + 2) = 3; 
printf("memory location x : %p\n",x); 

// 3. assignment, useless in case of previous memory allocation 
x = (int []) { 1, 2, 3 }; 
printf("memory location x : %p\n",x);