简体   繁体   English

malloc之后的Int Array初始化

[英]Int Array initialization after malloc

I got this little question about this int array initialization after I did memory allocation. 在进行内存分配后,我得到了关于这个int数组初始化的小问题。 I got below error: 我得到以下错误:

"Line 7 Error : expected expression before '{' token" “第7行错误 :'{'标记之前的预期表达式”

This is my code: 这是我的代码:

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

Is there any other way to initialize my array after I do memory allocation? 在进行内存分配后,还有其他方法可以初始化我的数组吗?

First of all, we must understand that the memory for array is allocated at heap memory area. 首先,我们必须了解数组的内存是在堆内存区域分配的。 Therefore we can initialize by following methods. 因此我们可以通过以下方法初始化。

  • using memcpy function 使用memcpy函数
  • pointer arithmetic 指针算术

Above two methods preserve the memory allocation through malloc function. 以上两种方法通过malloc函数保留内存分配。 But assignment through (int[]) {1,2,3} will cause memory wastage due to previous allocated heap memory. 但是通过(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM