Hi,
I'm trying to write my own version of the function calloc().
Below is the code.
Something goes wrong. The output when using my own calloc() is just random integers. The varibales in my_calloc don't seem to be local though, since the call a[0] in main gives the number assigned in my_calloc() (The code commented out).
1) somebody knows what's wrong?
2) if I correct it will my function my_calloc() work as the standard function calloc()?
Code:
// Trying out calloc()
#include <stdio.h>
#include <stdlib.h>
int *my_calloc(size_t n, size_t size);
int main(void)
{
int i, n;
int *a;
printf("Number of elements: ");
scanf("%d", &n);
//a = (int *) calloc(n, sizeof(int));
a = my_calloc(n, sizeof(int));
// Printfs just for test
printf("a[0]: %d\n", a[0]);
printf("a[1]: %d\n", a[1]);
printf("a[2]: %d\n", a[2]);
// End test
printf("Enter numbers: \n");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Numbers entered: \n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
int *my_calloc(size_t n, size_t size)
{
int mem[n];
int *ptr;
ptr = mem;
/* Just to test
mem[0] = 3;
mem[1] = 2;
mem[2] = 1;
printf("Inside my_calloc: %d\n", mem[0]);
*/
return ptr;
}