Home > Net >  I am getting 2 errors and long compilation time caused by one function in C
I am getting 2 errors and long compilation time caused by one function in C

Time:03-04

This is my function create

void create(int *array, int size)
{
    *array = (int *)malloc(size * sizeof(int));
}

Here I am trying to create dynamic table

Now in int main I am trying to make a pointer for a function create and then call it

int main(void)
{
int *array;
int size = 64;
void (*create_array)(int *, int) = create;
create_array(&array, size);
}

And here is the error that I am getting after F9 and really long compilation time:

In function 'create':
assignment makes integer from pointer without a cast [-Wint-conversion]|
In function 'main':
note: expected 'int *' but argument is of type 'int **'

I was trying to edit this function

void create(int *array, int size)
{
    array = (int *)malloc(size * sizeof(int));
}
or
void create(int *array, int size)
{
    int *ptr;
    *ptr = *array;
    *ptr = (int *)malloc(size * sizeof(int));
}

But my program crashes after this

CodePudding user response:

The warnings are because you need to declare the argument to create() as a pointer to a pointer:

void create(int **array, int size)
{
    *array = malloc(size * sizeof(int));
}

There's also no need for the cast and it's best avoided. See Do I cast the result of malloc?

CodePudding user response:

What you probably want is something like this:

void create(int **array, int size)
{
    *array = malloc(size * sizeof **array);
}

int main(void)
{
    int *array;
    int size = 64;
    void (*create_array)(int**, int) = &create;
    (*create_array)(&array, size);
}

To be able to pass the pointer to the allocated block back to main, you need another level of indirection (i.e., int** rather than int* for array). Also, your format for a funtion pointer was incorrect. Traditionally, an allocation function will give the pointer as a return value, in which case the code would look like this:

int *create(int size)
{
    return malloc(size * sizeof **array);
}

int main(void)
{
    int *array;
    int size = 64;
    int **(*create_array)(int) = &create;
    array = (*create_array)(size);
}

BTW, it is best to also check the return value from malloc in case the memory allocation failed.

  • Related