user123456789
user123456789

Reputation: 478

how do we pass the address of an int* to a function that uses void ** as parameter?

I have made a stack ADT using void pointers. here are the main and queueFront functions-

bool queueFront(QUEUE *queue, void **itemPtr){
    if(queue->count == 0)
        return false;

    *itemPtr = queue->front->dataPtr;
    return true;
}

int main(){
    QUEUE *queue = createQueue();
    int *x = new int(5);
    enqueue(queue,x);
    int *y =new int(10);
    enqueue(queue,y);
    int *getPtr{nullptr};

    queueFront(queue, (void *)&getPtr);
    std::cout << *getPtr << std::endl;
}

the book that i am currently using says to use "(void *)&getPtr" while calling queueFront but the compiler gives and error{"invalid conersion from void* to void**"}. I know that using (void **) works but i want to cast int* to void* and then use its address.

Upvotes: 0

Views: 89

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

You don't. A int** and a void** are two different things.

You should create a void* then use its address. You can then safely cast that back to int* if you know that it points to an int.

int main(){
    QUEUE *queue = createQueue();
    int *x = new int(5);
    enqueue(queue,x);
    int *y =new int(10);
    enqueue(queue,y);
    void *getPtr{nullptr};

    queueFront(queue, &getPtr);
    std::cout << *(int*)getPtr << std::endl;
}

Ideally you'd use a book that wasn't written in 1970 using ancient C idioms; we don't use void* pointers any more; we use templates.

Upvotes: 3

Related Questions