heap and pointers doubt !

I have learnt in class that heap can we accessed only by using pointers. I know that malloc function allocate memory in heap at runtime by using pointers .But when we declare an array globally in C , it also goes to heap yet we never use pointers for it. for example-

#include<stdio.h>
int arr[1000000];

int main()
{

 
}

how does that allocation is happening without using any pointer…?

1 Like

@va1ts7_100
Hi. actually question is not much clear…

but still whatever I have understood your question…

there are 2 types of declaration

  • 1). Static Declaration
  • 2). Dynamic Declaration

Static Declaration

i.e. int arr[100]

this implies you have assigned 100 x sizeof(int) to arr at compile time itself

Dynamic Declaration

i.e. int* arr=(int*) malloc(100*sizeof(int))
this is called runtime memory allocation because it happen at time runtime not compile time
as malloc() function which is defined in stdlib.h get memory from heap…

actually this is main difference…but practically(For competitive programmer) no difference…
somewhere I read [] operator simply overload to call malloc() function at compile time it self in static declaration
example ar[100]…

here I am attaching some links it might be helpful regarding to your doubts…

static vs dynamic declaration

operation overloading

You can also use static as well as dynamic memory allocation when declaring Arrays.

Like if you have a fixed length array, you can use both int a[<const>] and malloc().

But when you have a Runtime declaration, means, you don’t know the size of array, you have to use malloc() in C language, but in C++, it works equally well like C. so int a[<variable>] will work in C++.

The compiler automatically allocates a continuous memory in the RAM while decalring like int a[]. So feel free to understand question like that.

I am very happy to answer your question. Comment for more doubts. :slight_smile:

1 Like

int arr=(int)malloc(100*sizeof(int))

@ bradely can we use map or set or other inbuilt data structure in contest using c++??

Yes Brother, you can fully use them.

Just add an include statement such as , , etc and it will include all the necessary classes and Data Structures

@rcsldav2017, my question is that , when i declare an array globally without using malloc function , it occupies memory in heap rather than stack ! why is is happeneing …?? can we declare memory in heap without using malloc or calloc fns…??

@bradely, first of all i code in C language only.! so can i declare an array without using malloc or calloc functions and it occupies space in heap , rather than stack…?