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.
You aren’t actually reallocating
list.listis still5bytes, whileptrpoints to the10byte array.Do something like this instead:
Now, when you say:
You aren’t creating a “reference” to
list; in this context (not in general), it’s the same as:This means
ptr[3]andlist[3]are the sameint, but makingptrpoint to a new buffer won’t makelistpoint to a new buffer as well. If this were C++, the syntax for declaringptrthe way you’re thinking would be (I think):In any case, you can’t
reallocan automatically-allocated buffer, anyway. This won’t work:The
reallocwould likely cause a segmentation fault, and assigning the new pointer tobufferisn’t allowed by C.Finally, stealing from the other answers, you need to
#include <stdlib.h>to usemallocand friends; otherwise, it’ll be implicitly declared to return anintrather than a pointer, yielding warnings and screwing up 64-bit compatibility for no good reason.