473,385 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

what is the use of void pointer?

i do not know what is the use of (e.g. void *pt), when will use it.

thanks!
Nov 20 '05 #1
22 28940
Viv
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.

Nov 20 '05 #2
Viv wrote:
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.


A good example is the "malloc" function. It returns a void* and you can
typecast it to whatever type you need.

Prototype : void *malloc(size_t size);
Usage : int *n = (int *) malloc(sizeof(int));

Nov 20 '05 #3
Sandeep wrote:

Viv wrote:
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.
A good example is the "malloc" function.
It returns a void* and you can
typecast it to whatever type you need.


"Typecasting" is something that happens to thespians.

http://dictionary.reference.com/search?q=typecast&db=*
Prototype : void *malloc(size_t size);
Usage : int *n = (int *) malloc(sizeof(int));


A more better way, is without the cast.

int *n = malloc(sizeof *n);

--
pete
Nov 20 '05 #4
Sandeep wrote:
Viv wrote:
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.


A good example is the "malloc" function. It returns a void* and you can
typecast it to whatever type you need.

Prototype : void *malloc(size_t size);
Usage : int *n = (int *) malloc(sizeof(int));


That is terrible usage of malloc, and I'm sure you have been here long
enough to have seen the generally recommended usage of

int *n = malloc(sizeof *n);

You don't need to cast the return value of malloc, and doing so can
prevent the compiler from warning you about not having a declaration of
malloc in scope. Also, the form you showed means having to get the type
correct three times instead of once, having to check it in three places,
and having to change it in three places instead of one if it needs changing.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 20 '05 #5
> That is terrible usage of malloc, and I'm sure you have been here long
enough to have seen the generally recommended usage of

int *n = malloc(sizeof *n);

You don't need to cast the return value of malloc, and doing so can
prevent the compiler from warning you about not having a declaration of
malloc in scope. Also, the form you showed means having to get the type
correct three times instead of once, having to check it in three places,
and having to change it in three places instead of one if it needs changing.


I was trying to explain the use of "void *" and though that to a newbie
it would have been easier to understand it as
int *n = (int *)malloc(sizeof(int));

But Point Taken, I should not explain one concept in a way that gives a
not so correct information about some other concept.

Nov 20 '05 #6
Sandeep wrote:
I was trying to explain the use of "void *"
and though that to a newbie
it would have been easier to understand it as
int *n = (int *)malloc(sizeof(int));

But Point Taken,
I should not explain one concept in a way that gives a
not so correct information about some other concept.


It's not some other concept.
The lack of cast
is the reason for the existence of the pointer to void type.
Previous to the invention of the pointer to void type,
the pointer to char type was used to accomplish the same tasks.

--
pete
Nov 20 '05 #7
pete wrote:

Sandeep wrote:
I was trying to explain the use of "void *"
and though that to a newbie
it would have been easier to understand it as
int *n = (int *)malloc(sizeof(int));

But Point Taken,
I should not explain one concept in a way that gives a
not so correct information about some other concept.
It's not some other concept.
The lack of cast
is the reason for the existence of the pointer to void type.


"use" is a better word to use there, than "existence".
It's existence follows logically from the invention of
type void.
Previous to the invention of the pointer to void type,
the pointer to char type was used to accomplish the same tasks.


--
pete
Nov 20 '05 #8
pete <pf*****@mindspring.com> writes:
Sandeep wrote:
I was trying to explain the use of "void *"
and though that to a newbie
it would have been easier to understand it as
int *n = (int *)malloc(sizeof(int));

But Point Taken,
I should not explain one concept in a way that gives a
not so correct information about some other concept.


It's not some other concept.
The lack of cast
is the reason for the existence of the pointer to void type.
Previous to the invention of the pointer to void type,
the pointer to char type was used to accomplish the same tasks.


I wouldn't say that the lack of a cast operator is the reason for the
existence of void*. void* is a generic pointer type. It needs to be
convertible to any pointer-to-object type, but the fact that it's
*implicitly* convertible is just a convenience. One can imagine a
C-like language in which void* is not implicitly convertible, but is
still useful (and one might imagine calling this hypothetical language
C++).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 20 '05 #9
>
It's not some other concept.
The lack of cast
is the reason for the existence of the pointer to void type.
Previous to the invention of the pointer to void type,
the pointer to char type was used to accomplish the same tasks.

--
pete


K & R - Second Edition

Section 6.6

Char *strdup(char *s)
{
char *p;
p = ( char *) malloc(strlen(s) + 1) ;
......
}

K & R
Section 7.8.5
The pointer returned by malloc has the proper alignment for the object
in question, but it must be cast into the appropriate type.

PS : "void *" existed at the point this edition went into press.

Things might have changed a lot, but
int *p = (int *) malloc ( sizeof(int) ); , is NOT a SIN.

- Sandeep

Nov 20 '05 #10
On 20 Nov 2005 10:48:19 -0800, in comp.lang.c , "Sandeep"
<sa************@gmail.com> wrote:
K & R - Second Edition
Read the errata.
p = ( char *) malloc(strlen(s) + 1) ;
which specifically mentions that the cast was a mistake...
K & R
Section 7.8.5
The pointer returned by malloc has the proper alignment for the object
in question, but it must be cast into the appropriate type.
same point.
Things might have changed a lot, but
int *p = (int *) malloc ( sizeof(int) ); , is NOT a SIN.


Ben Pfaff has I believe a useful page all about hte sinfulness of
casting the return from malloc.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 20 '05 #11
Sandeep wrote:

It's not some other concept.
The lack of cast
is the reason for the existence of the pointer to void type.
"use" is the correct word, rather than "existence".
Previous to the invention of the pointer to void type,
the pointer to char type was used to accomplish the same tasks.
K & R - Second Edition PS : "void *" existed at the point this edition went into press.


K & R First Edition is older than void.

Chapter 8, Section 8.7

free(ap) /* put block ap in free list */
char *ap;
{

....

--
pete
Nov 20 '05 #12
Mark McIntyre wrote:

On 20 Nov 2005 10:48:19 -0800, in comp.lang.c , "Sandeep"
<sa************@gmail.com> wrote:
K & R - Second Edition


Read the errata.


http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

--
pete
Nov 20 '05 #13
(Before we get into the meat of this subject, I'd just like to agree with a
number of people who have pointed out that casting a void pointer is almost
always utterly pointless. There, done that - now, on with the show...)

nick said:
i do not know what is the use of (e.g. void *pt), when will use it.


A void pointer is useful when you are writing code which does not know the
type of the data being presented to it, but which can do one of (at least)
two things:

(a) assume a particular representation;
(b) pass the data to a function that /does/ know the type.

Here is an example of the first of those:

void *memcpy(void *dest, const void *src, size_t len)
{
unsigned char *d = dest;
const unsigned char *s = src;
while(len--)
{
*d++ = *s++;
}
return dest;
}

(In practice, memcpy would probably be implemented much more cleverly than
this - but the above would work just fine.) Because memcpy's job is simply
to copy data from one place to another, it can legitimately treat src as a
mere sequence of bytes.

Here is an example of the second item in my list, where we don't process the
data at all, but simply pass it on to a function whose address the caller
gives us.

#include <stdio.h>

void iterate(void *p,
size_t size,
size_t num,
void (*iterfunc)(void *, void *),
void *args)
{
size_t i;
unsigned char *e = p;
for(i = 0; i < num; i++)
{
(*iterfunc)(e + i * size, args);
}
}

void foreachint(void *vpi, void *vfp)
{
int *pi = vpi;
FILE *fp = vfp;
fprintf(fp, " %d", *pi);
}

void foreachdouble(void *vpd, void *vfp)
{
double *pd = vpd;
FILE *fp = vfp;
fprintf(fp, " %f", *pd);
}

int main(void)
{
int foo[] = { 3, 1, 4, 1, 5, 9, 2, 6 };
double bar[] = { 0.1, 0.2, 0.3 };
iterate(foo,
sizeof foo[0],
sizeof foo / sizeof foo[0],
foreachint,
stdout);
putchar('\n');
iterate(bar,
sizeof bar[0],
sizeof bar / sizeof bar[0],
foreachdouble,
stdout);
putchar('\n');
return 0;
}

In case you hadn't already guessed, the output of this program is:

3 1 4 1 5 9 2 6
0.100000 0.200000 0.300000

There are better ways to handle abstract data in C, but this is a reasonably
good way to ease yourself gently into the concept.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Nov 20 '05 #14
On 20 Nov 2005 00:16:39 -0800, "Viv" <as******@cadence.com> wrote in
comp.lang.c:
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.


Why are you talking to 'u'? He hasn't read this group in years!

Then there is the fact that your answer needs something to be desired.
You don't need to cast a void pointer to a pointer to any type of
object, and while you can cast a void pointer to some non-pointer data
types, namely integer types, it is usually not a good idea.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 21 '05 #15
Mark McIntyre wrote:
On 20 Nov 2005 10:48:19 -0800, in comp.lang.c , "Sandeep"
<sa************@gmail.com> wrote:
K & R - Second Edition


Read the errata.
p = ( char *) malloc(strlen(s) + 1) ;


which specifically mentions that the cast was a mistake...


Your interpretation of "The example is correct and works"
is different to mine!

Here's the relevant errata...

"142(§6.5, toward the end): The remark about casting the
return value of malloc ("the proper method is to declare...
then explicitly coerce") needs to be rewritten. The example
is correct and works, but the advice is debatable in the
context of the 1988-1989 ANSI/ISO standards. It's not
necessary (given that coercion of void * to ALMOSTANYTYPE *
is automatic), and possibly harmful if malloc, or a proxy for
it, fails to be declared as returning void *. The explicit
cast can cover up an unintended error. On the other hand,
pre-ANSI, the cast was necessary, and it is in C++ also."

It says that the _remark_ needs to be rewritten as the advice is
debatable. That is not the same as saying the cast was a mistake.

The Preface to K&R2 states they used a C++ compiler to originally
test sample code. In the absence of any other commentary from the
authors, I can easily imagine that the code would remain the same,
however the remark would be changed to say that the cast is not
required.

<snip>
Things might have changed a lot, but
int *p = (int *) malloc ( sizeof(int) ); , is NOT a SIN.


Ben Pfaff has I believe a useful page all about hte sinfulness of
casting the return from malloc.


You mean...?

http://benpfaff.org/writings/clc/malloc-cast.html.

At least Ben had the good sense to acknowledge that some
(respectable) C programmers disagree...

"I agree that you have to write more casts in C++ than in C,
and I agree that casts can sometimes disguise other problems.
But it's been my experience over the past ten years that casts
tend to hide stupid bugs, which are relatively easy to find,
while compiling as C++ tends to find subtler bugs, which are
not. The tradeoff has been well worth it for us."

- P.J. Plauger

--
Peter

Nov 21 '05 #16
Hi all,

Apart frm all that healthy discussion abt void ptrs, i would like to
add one more usage of void ptrs.

void ptrs can be used to create NULL pointers. A constant 0 or any
expression resulting in 0, when casted into (void*) is known as a NULL
ptr. such a NULL ptr can be used for comparing pointers. it will always
be unequal when compared to a legal pointer value.

its a good programming practice in comparing pointers like this

thanx

Nov 21 '05 #17
aa**********@matrixtelesol.com wrote:
A constant 0 or any expression resulting in 0,
when casted into (void*) is known as a NULL ptr.


Not exactly.
NULL, is a macro which expands to a null pointer constant.

Any constant expression
with an integer type that compares equal to zero,
is already a null pointer constant,
with or without the (void *) cast.

When you write "NULL pointer"
nobody knows whether you mean
1 the NULL macro
2 a null pointer constant
3 a null pointer

A null pointer,
is any pointer of any type
that compares equal to a null pointer constant.

--
pete
Nov 21 '05 #18
pete wrote:

aa**********@matrixtelesol.com wrote:
A constant 0 or any expression resulting in 0,
when casted into (void*) is known as a NULL ptr.
Not exactly.
NULL, is a macro which expands to a null pointer constant.

Any constant expression
with an integer type that compares equal to zero,
is already a null pointer constant,
with or without the (void *) cast.

When you write "NULL pointer"
nobody knows whether you mean
1 the NULL macro
2 a null pointer constant
3 a null pointer


Actually,
those are what I would have assumed that you might have meant,
if you hadn't already defined "NULL pointer" as term,
meaning something that you just made up.
A null pointer,
is any pointer of any type
that compares equal to a null pointer constant.


--
pete
Nov 21 '05 #19
Viv <as******@cadence.com> wrote:
You should use it when you do not know what data type the memory
contains. The advantage is that once u know the data type, u may
typecast the void ptr into the appropriate data type.


Actually the advantage is, that you don't have to type cast that void
pointer, but can assign it directly to some pointer of the designated
type.
--
Z (zo**********@web.de)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Nov 21 '05 #20
"nick" <i1********@yahoo.com> wrote in message
news:dl***********@justice.itsc.cuhk.edu.hk...
i do not know what is the use of (e.g. void *pt), when will use it.


It's a pointer to location zero in memory, of course <gd&rvvvf> ;-)

--
Mabden
Nov 25 '05 #21
Sandeep a écrit :
Usage : int *n = (int *) malloc(sizeof(int));


What about

Usage : int *n = malloc (sizeof *n);

- No cast required
- Reduced maintenance :

Usage : double *n = malloc(sizeof *n);

--
A+

Emmanuel Delahaye
Nov 25 '05 #22
Sandeep a écrit :
K & R - Second Edition char *p;
p = ( char *) malloc(strlen(s) + 1) ;


http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

--
A+

Emmanuel Delahaye
Nov 25 '05 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Niks | last post by:
what is a void pointer?
52
by: Douglas Garstang | last post by:
I can't believe I've been trying to work this out for hours now, and I can't believe I couldn't find someone asking for a similar solution in the newsgroups. No wonder I hate C so much, and every...
22
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do...
9
by: Juggernaut | last post by:
I am trying to create a p_thread pthread_create(&threads, &attr, Teste, (void *)var); where var is a char variable. But this doesnt't work, I get this message: test.c:58: warning: cast to pointer...
12
by: Andreas Schmidt | last post by:
I am trying to understand the behavior of void pointers. Can someone explain to me why I get a segfault for the following program? #include <stdio.h> void* plusone(void* i){ int* arg =...
23
by: Eric J.Hu | last post by:
Hi, I have following code, want do pointer convert. It always complain: vcnvt.c: In function `main': vcnvt.c:20: warning: dereferencing `void *' pointer vcnvt.c:20: request for member `key'...
27
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in...
5
by: Niu Xiao | last post by:
I saw a lot of codes like: void foo(void* arg) void bar(void** arg) f((void*)p) but what does void pointer mean in c? I just know it stands for generic pointer. thanks.
49
by: elmar | last post by:
Hi Clers, If I look at my ~200000 lines of C code programmed over the past 15 years, there is one annoying thing in this smart language, which somehow reduces the 'beauty' of the source code...
10
by: kkirtac | last post by:
Hi, i have a void pointer and i cast it to an appropriate known type before using. The types which i cast this void* to are, from the Intel's open source computer vision library. Here is my piece...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.