Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c - How to verify if a void pointer (void *) is one of two data types?

I am writing a function where i would like to accept 2 types of parameters.

  • A string (char *)
  • A structure where there will be n number of elements.

And to achieve this i am thinking of using a simple void * as parameter type. But i do not know how to verify if the parameter is one type or the other, safely.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The translation of void* is
"Dear compiler, this is a pointer, an there is no additional information for you on this.".

Usually the compiler knows better than you (the programmer), because of information he got earlier and still remembers and you might have forgotten about.
But in this special case, you know better or need to know better. In all cases of void* the information is available otherwise, but only to the programmer, who "happens to know". The programmer therefor has to provide the information to the compiler - or better to the running program, because the one advantage a void* has is that the information can change during runtime.
Usually that is done by giving the information via additional parameters to functions, sometimes via context, i.e. the program "happens to know" (e.g. for each possible type there is a separate function, whichever function gets called implies the type).

So in the end void* does not contain the type info.
Many programmers misunderstand this as "I don't need to know the type info".
But the opposite is true, the use of void* increases the responsibility of the programmer to keep track of the type info and provide it appropriatly to the program/compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...