This code has several errors. First of all, the warning refers to the fact that you're trying to assign a pointer to integer (int *
) to a variable (a
) which is a pointer to a pointer to integer (int **
), which you actually want to use as an array of arrays.
So, first correction, at line 8 it's not
a=(int*)malloc(sizeof(int)*5);
but it is
a=(int**)malloc(sizeof(int *)*5);
(that cast in C isn't strictly necessary, but being a C++ programmer I prefer to keep it like that)
Notice that also the expression in the sizeof
changed, since what you want to allocate is not the space for five integers, but the space for five pointers to integers.
Then, at the end of the application, you're free
ing just the space allocated with the first malloc
, while you made other five allocations (one for each row). Thus, you could do the deallocation in the last cycle, just after displaying each row.
for (i=0; i<5; i++)
{
for (j=0; j<3; j++)
{
printf("\nthe value enter enter the [%d][%d] location = ",i,j);
printf("%d",a[i][j]);
}
free(a[i]);
a[i]=NULL;
}
free(a);
a=NULL;
Remember: for each malloc
or calloc
, you have to have it's corresponding free
, otherwise you're leaking memory.
Here, after each deallocation, I set the corresponding pointer to NULL
to throw away those old, now-invalid, pointers. Somebody say that this behavior can mask double-frees (since free(NULL)
doesn't produce errors), but IMHO this is better than the alternative
One important detail: you're not checking the return value of malloc
, which is quite bad. It's extremely unlikely that in such small programs allocations may fail, but, nonetheless, it's good practice to always check if the return value of malloc
is NULL
, and, in this case, handle the situation gracefully, usually releasing all the resources and shutting down the application.
By the way, system("clear");
is ugly. You should use the platform-specific way to clean the screen, even better if enclosed in a function; on Linux with normal (X3.64) terminal emulators something like this could be ok:
void ClearScreen()
{
fputs("\x1B[2J\x1B[1;1H", stdout);
fflush(stdout);
}