Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc or normal array definition?

Tags:

arrays

c

malloc

When shall i use malloc instead of normal array definition in C?

I can't understand the difference between:

int a[3]={1,2,3}
int array[sizeof(a)/sizeof(int)]

and:

array=(int *)malloc(sizeof(int)*sizeof(a));
like image 674
Antonio Ciccia Avatar asked Jun 28 '12 08:06

Antonio Ciccia


1 Answers

In general, use malloc() when:

  • the array is too large to be placed on the stack
  • the lifetime of the array must outlive the scope where it is created

Otherwise, use a stack allocated array.

like image 80
hmjd Avatar answered Nov 10 '22 10:11

hmjd