Вопрос

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.

Это было полезно?

Решение 2

This compiles with no warning

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

Другие советы

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 *));

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top