'Why any type can be assigned void* but I can not return void* for any type function? [closed]

Why can I make for example

void *j;
int *intpointer = j;

But I can not make

int ** function(){
    void **j;
    return j;
}

I understand that for example that void* a = "any type" because void* accepts any type,, but why for example any type like int* can be assigned a void* type? If it is int* it should be assigned int* type, why does it accept void * type? I am trying to understand this:

 void *j;
 int* a = j


Solution 1:[1]

In C the void * is indeed the any type. So when you assign a void* to an int* then the compiler assumes you know what you are doing. Switching pointers to void and back happens quite a lot in generic programming or every time you malloc() or free() and C programmers are lazy. They don't want to cast that case every time.

Note: A frequent pattern for this is that an int* gets passed to a function accepting a void* and then passed to a callback that casts it back to int * because it knows that it originally was an int*. Similar for generic storage containers. You put in an int* by changing it to void* so when you get it back out you change it back to int*.

Note: it is important that you only assign a void* to int* when you know it is pointing at an int, i.e. it was previously changed from int* to void*. Otherwise you enter undefined behavior territory.

Even for other pointer types C assumes you know what you are doing and it is only a warning:

<source>:2:12: warning: returning 'short int *' from a function with incompatible return type 'int *' [-Wincompatible-pointer-types]

In those case the compiler (gcc here) wants you to explicitly cast the pointer before returning to signal that this was intentional. Because it is very rare that this actually makes sense.

If you get errors for any of this then you are likely trying to compile the source as C++ and not C.

Solution 2:[2]

If you want the data on the client side, you can create an api route and send the data as json.

If you just want the data in another js file, then you can just require the db model in the file and use db find to use the result there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 thecodenoob