Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in C and malloc

Tags:

c

malloc

1.How the two dimension stored in the memory, are they consecutive? (I mean the int[M][N], not the dynamic allocation, I think the int[M][N] happened in the stack area, so continual, isn't it?)

2.Does the area allocated by malloc must is consecutive?

3.If there is no need to dynamic allocate memory space, where should I use? stack or heap. For example, I want a char array to store 10000 chars, so should I use:

char a[10000];

or

char *a = calloc(sizeof(char),10000);

Is the "function call stack" in the same area as the variable stack??In the same stack or different?

like image 393
iLeoDo Avatar asked Dec 04 '25 13:12

iLeoDo


1 Answers

In int numbers[m][n] the n's are consecutive ints in memory, e.g. numbers[0][0] is followed by numbers[0][1].

On the other hand, lets say n=10, then numbers[m][9] is followed by numbers[m+1][0].

malloc returns consecutive memory. you decide how to use it.

A 10000 byte array on the stack is no problem unless the function is recursive and (as Carey notes) unless you are developing in a small stack environment ie. embedded.

Yes the callstack and local variables are identical.

like image 181
Bernd Elkemann Avatar answered Dec 07 '25 15:12

Bernd Elkemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!