In my program I am trying to resize array using malloc function.
#include <stdio.h>
int main(void)
{
int list[5],i;
int* ptr = &list;
for(i = 0; i < 5; i++)
list[i] = i;
for(i = 0; i < 5; i++)
printf("%d\n", list[i]);
printf("----------------------------------------\n");
ptr = malloc(10);
for(i = 0; i < 10; i++)
list[i] = i;
for(i = 0; i < 10; i++)
printf("%d\n", list[i]);
}
While compiling the program I get two warnings :
searock@searock-desktop:~/C$ cc malloc.c -o malloc
malloc.c: In function ‘main’:
malloc.c:6: warning: initialization from incompatible pointer type
malloc.c:16: warning: incompatible implicit declaration of built-in function ‘malloc’
My program is running fine. I can't understand why the compiler is giving me this errors?
Should I change my approach?
Edit 1 : And then how do I free the memory? should I use free(list); or free(ptr);
Edit 2 : Updated Code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int list[5],i;
int* ptr = malloc(5 * sizeof(int)); //&list;
for(i = 0; i < 5; i++)
ptr[i] = i;
for(i = 0; i < 5; i++)
printf("%d\n", ptr[i]);
printf("----------------------------------------\n");
ptr = realloc(ptr, 10 * sizeof(int)); //malloc(10);
for(i = 0; i < 10; i++)
ptr[i] = i;
for(i = 0; i < 10; i++)
printf("%d\n", ptr[i]);
free(ptr);
}
Thanks.