So apparently dynamic memory allocation allows memory to be allocated during runtime instead of compile time like static memory allocation. I also understand that using these functions in malloc.h we can save memory by unassigning memory blocks which are not in use by using free(). But my confusion lies in whether the following code comes under dynamic memory allocation or not.
#include <stdio.h>
int main() {
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++){
printf("%d",a[i]);
}
return 0;
}
How is malloc.h functions beneficial in a case where I want the user to specify the size when the above code serves the purpose of allocating during runtime? How are malloc, calloc and realloc different from each other?
Also, what if malloc is being used as follows:
ptr=(int*)malloc(3*sizeof(int));
How is this different from
int ptr[5];
If the memory required is unknown during writing of the code, can I not declare a pointer and then simply do a ++ to store value in the next memory address as follows?
int* ptr;
while(1){
scanf("%d",ptr);
ptr++;
}
Jennie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.