0

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

Coonvert
  • 3
  • 1
  • In `int *ptr; *ptr = *array;` you are dereferencing an unitialised pointer. The following line `*ptr = (int *)malloc(size * sizeof(int));` repeats the same crime. I guess it was meant to be `ptr = (int *)malloc(size * sizeof(int));` but it's still *after* being dereferenced. – Weather Vane Mar 03 '22 at 18:45
  • The second version of `create` makes no sense. You should assign the result of `malloc()` to `ptr`, then do `*array = ptr`. – Barmar Mar 03 '22 at 18:47
  • the long compilation time probably has nothing to do with the code you've posted. There's probably some code in the program that can be executed at compile time, so the compiler is doing that. – Barmar Mar 03 '22 at 18:48

2 Answers2

0

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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.

SGeorgiades
  • 1,771
  • 1
  • 11
  • 11