简体   繁体   中英

Converting a int pointer to a void pointer and back to use the value in another function?

I would like to convert a int pointer to a void pointer and pass that void pointer to a function and then back to an int pointer to use that value in another function.

void main(){
    int newSize = size;
    void *newSizePtr = &newSize;
    someFunc(newSizePtr);
}

void someFunc(void *newSizePtr){
    int actualValue = *((int *) newSizePtr);
}

Is this the right way to convert a int ptr to a void ptr and then back to use the value?

i am unable to dynamically allocate memory to the pointer itself because of restrictions with my program that i cannot use malloc. ie

int *newSize = malloc(sizeof(int));

which is why i did it this way.

i also need to pass in a void* argument because in my program i am using pthread_create(). This function requires me to pass in an argument of a void* to the function which is why i casted it to a void* and then back when i needed to use it

The conversion you are doing is explicitly allowed by the C standard . Section 6.3.2.3p1 regarding pointer conversions states:

A pointer to void may be converted to or from a pointer to any object type. A pointer toa ny object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

It's also not necessary to explictily cast to or from a void * . So you can do something like this:

void someFunc(void *newSizePtr){
    int *actualValuePtr = newSizePtr;
}

int main(){
    int newSize = size;
    pthread_t tid;
    pthread_create(&tid, NULL, someFunc, &newSize);
}
#include <stdio.h>
#include <memory>

void someFunc(void*);

int main() {

    int size = 4;

    int newSize = size;

    void* newSizePtr = &newSize;

    someFunc(newSizePtr);

    // void* -> int*, before using
    int* newSize = (int*) malloc(sizeof(int));

}

void someFunc(void* newSizePtr) {

    int actualValue = *((int*)newSizePtr);

    printf("%d", actualValue);

}

Yes you can cast void* to int*, and int* to void *,

Because, void * is 'generic' pointer.

malloc returns generic pointer (void*) because malloc does not know what 'type' of return you need.

So, you need to convert to the type you need.

(In the above code, you need to convert to void* -> int*)

For more information about usage of generic pointer, below link may help you

https://codexpart.com/what-is-generic-pointer-difference-between-generic-pointer-and-void-pointer/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM