【问题标题】:Int Array initialization after mallocmalloc 后的 Int 数组初始化
【发布时间】:2017-08-01 05:19:44
【问题描述】:

在进行内存分配后,我收到了一个关于这个 int 数组初始化的小问题。我收到以下错误:

“第 7 行错误:'{'标记之前的预期表达式”

这是我的代码:

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

在我分配内存后还有其他方法可以初始化我的数组吗?

【问题讨论】:

    标签: arrays memory allocation


    【解决方案1】:

    首先,我们必须了解数组的内存分配在堆内存区域。因此我们可以通过以下方法进行初始化。

    • 使用 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);
    

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 2021-10-20
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多