Double pointer in c, assignment warning for my code

239 views Asked by At

I don't know why I am getting warnings for the following code.

#include<stdio.h>
#include<malloc.h>
int main()
{
    int **p;
    int i,j;
    for(i=0;i<5;i++)
    {
        if(i==0)
            p=(int*)malloc(1*sizeof(int));
        else
            p=(int*)realloc(p,(i+1)*sizeof(int));
        p[i]=(int*)malloc(5*sizeof(int));

        for(j=0;j<5;j++)
        {
           p[i][j]=j;
        }
    }
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
            printf("%5d",p[i][j]);
        printf("\n");
    }

    return 0;
}  

Is there any other way to allocate memory dynamically for a double pointer.

3

There are 3 answers

7
stark On BEST ANSWER

This compiles with no warning

  int **p;
  p = (int **) malloc(sizeof(void *));
0
trogdor On

You get warnings because p is an int ** and you are allocating memory as if it was an int * in your if..else lines. Simply replace your lines as follows:

p=(int **)malloc(1*sizeof(int *));

p=(int **)realloc(p,(i+1)*sizeof(int *));
0
This isn't my real name On

You're getting warnings because you're (a) casting the return value of malloc() and realloc(), and (b) casting it to the wrong type. In C it's generally considered best not to cast the return value of malloc() and realloc() at all, because void* will automatically convert to any other pointer type, and putting in the unnecessary cast can lead to errors (such as yours, for example).