'Dynamic memory allocation confusion
I saw a tutorial where the instructor dynamically allocates memory for n*int size (n is not known in advance, user would give it as an input). Just out of curiosity, I have changed the code from calloc(n,sizeof(int)) to calloc(1,sizeof(int)) and I was expecting to see an error, but I did not face an error, and the code runs smoothly.
If I increment the pointer and it just continues without a problem, why should I use anything else but calloc(1,sizeof(int))?
#include <iostream>
using namespace std;
int main(){
int n;
printf("enter the size of array\n");
scanf("%d",&n);
int* A = (int*)calloc(1,sizeof(int));
for(int i=0; i<n; i++){
*(A+i) = i+1;
}
for(int i=0; i<n; i++){
printf("%d\n", A[i]);
printf("%d\n", &A[i]);
}
// free(A)
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
