Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use a void pointer in this code?

Tags:

c++

#include <iostream> using namespace std; int main() {     char *pc;      int *pi;     double *pd;      pc = (char *)10000;              pi = (int *)10000;               pd = (double *)10000;                // 1)     cout << "before pc = " << (void *)pc << " pi = " << pi << " pd = " << pd << endl;      pc++;     pi++;     pd++;     // 2)     cout << "after increase pc = " <<  (void *)pc << " pi = " << pi << " pd = " << pd << endl;      return 0; } 

In this code(1, 2), why is variable pc cast to a void pointer?

I am checking that a run-time error does not occur if you do not print the variable pc.

like image 390
JaeHyuk Lee Avatar asked Sep 22 '14 08:09

JaeHyuk Lee


People also ask

What does void do in code?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.

What is void pointer in embedded C and why is it used?

Void pointers in C programming are the pointer variables which has no specific data type. These are also called as Generic pointers because it can point to any data type. In General, the compiler has no idea what type of object a void Pointer really points to.

What is the use of void in C?

The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.

What is void pointer example?

Example of pointer in Cint a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a! int a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a!


2 Answers

Because otherwise, the overloaded operator << (std::ostream&, const char*) would be called, which doesn't print an address, but a C-string.

For example:

std::cout << "Boo!";  

prints Boo!, whereas

std::cout << (void*)"Boo!"; 

prints the address that string literal is located at.

like image 42
Luchian Grigore Avatar answered Sep 19 '22 07:09

Luchian Grigore


Because char* when printed using cout << something will try to print a string (cout << "Hello, World" << endl; uses char * [pedantically, in this example, a const char *] to represent the "Hello, World").

Since you don't want to print a string at address 10000 (it would MOST LIKELY crash), the code needs to do something to avoid the pointer being used as a string.

So by casting to void* you get the actual address printed, which is the default for pointer types in general, EXCEPT char *.

like image 107
Mats Petersson Avatar answered Sep 21 '22 07:09

Mats Petersson