Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c - Malloc or normal array definition?

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...