Can we store values in the pointers as in the above program?
The only values that should be assigned to pointer variable are:
- addresses of other objects (such as
int *foo = &x;
);
- addresses of functions (
int (*fptr)(const char *, ...) = printf;
);
- addresses of well-defined system access points (such as a communications port or an interrupt register on an embedded system);
NULL
(which represents a well-defined "nowhere").
You should not use pointer variables to store arbitrary values for arithmetic computation or display as you do in your example.
The declaration
void *ptr=10;
should have raised a diagnostic; you cannot directly assign an integer value to a pointer variable without a cast. You might want to raise the warning level on the compiler you're using.
The statement
printf("%u",ptr);
invokes undefined behavior, since the type of the argument (void *
) doesn't match what the conversion specifier is expecting (unsigned int
). It "worked" in the sense that it displayed the value you expected, but that's a matter of luck, not design. It could just as easily have printed out a garbage value.
What is the main use of void pointer?
It serves as a "generic" pointer type. Pointers to different types are not directly assignable to each other; IOW, you can't do something like
char *foo;
double *bar;
foo = bar; // bzzt
without explicitly casting bar
to char *
:
foo = (char *) bar;
Similarly, if you have a function that takes a pointer parameter of one type, you can't call it with a pointer of a different type:
void f(char *);
...
double x;
f(&x); // bzzt
The one exception to this rule is objects of void *
type; they can be assigned without needing a cast:
int x;
void *foo = &x;
and functions that take paramters of type void *
can accept arguments of any object pointer type:
void f(void *);
...
double x;
int y;
f(&x);
f(&y);
They're used to implement limited forms of "generic" programming (where the algorithm is the same, but the types are different). The canonical example is the qsort
library function, which can sort arrays of any type.