- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
assigning a void pointer to another
I am working on this method that should operate the insertion sort on a given array of unknown type
I was thinking about doing something like memcpy() but I still don't know the size of the type.
- void-pointers

- @user17732522 corrected – ramaswag Aug 18, 2022 at 20:30
- 1 What do you want to achieve? This sounds like an XY-problem . – the busybee Aug 18, 2022 at 20:34
- 3 @ramaswag: Given a void * , it is impossible to assign the value of the thing it points to to another thing without knowing the type. That is because void * conveys no information about the object it points to, not even its size. It could be a one-byte char , a two-byte integer, an array of a million bytes, or something else. With just the pointer, the program does not know how many bytes to copy, let alone how the data in those bytes should be interpreted. – Eric Postpischil Aug 18, 2022 at 20:49
- 2 Assigning pointers doesn't copy the data that they point to. – Barmar Aug 18, 2022 at 20:49
- 3 "but I still don't know the size of the type." - ever wonder why functions like qsort require both the sequence element count and the size of the element type within the sequence? I bet you're no longer wondering. – WhozCraig Aug 18, 2022 at 21:14
If you want to sort an array whose element type is unknown to you, then you should use the signature of the standard qsort() function, which does exactly the same job. The signature presented in the question is similar, but not the same, and I see no good reason for the difference if the function's job is what you describe.
No, you don't, unless the the caller tells you . That information is not carried by type void * (nor type void ** ). That's why the arguments to qsort() are, and those to your function should be,
- a pointer to the first element of the array (type void * would be the most appropriate for that)
- the number of elements in the array
- the size of the element type
- a pointer to a comparison function that accepts pointers to array elements as arguments (again, void * is the most appropriate type for this).
HOWEVER, if the problem were slightly different, say "sort an array of pointers to void based on the order defined by a user-defined function that compares the objects to which the pointers point", then you don't need the size of the pointed-to objects, because you never need to move them. You move only the pointers. That might have this signature:
, which is equivalent to this:
Note the difference between this comparison function and your example . This describes a sort specifically of arrays of void * , where the sort order is user-defined and might depend on the pointed-to objects. You don't need the size of the pointed to objects here, because what you're supposed to sort (and therefore swap) is the pointers:
- My reasoning behind this is: 1) if I need an object that is for example an int or a float, i should declare it void* 2) if I need an object that is a pointer to an int or a pointer to a float that would be void** So if I need to compare or swap two addresses wouldn't they be void**? Why am I wrong? – ramaswag Aug 19, 2022 at 9:06
- 1 @ramaswag, I think you're missing why you pass a void * to the first array element to specify an array. That's not a stand-in for int in the case of sorting an int array (for example). Rather, it is a stand in for pointer to int a.k.a int * , which is what you would pass to a function that was specific to sorting arrays of int . – John Bollinger Aug 19, 2022 at 13:31
- 1 @ramaswag, as for the comparison function, it accepts pointers to the elements to compare. The most natural type for a pointer that might point to an object of any type is void * . Type void ** , on the other hand, is specifically a pointer to an object whose type is exactly void * . – John Bollinger Aug 19, 2022 at 13:39
- @ramaswag, again, the qsort() signature does the job you describe, and has done so very well for nearly half a century. If you're still not getting it then I recommend working some exercises involving using qsort() to sort arrays. – John Bollinger Aug 19, 2022 at 13:41
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .
Not the answer you're looking for? Browse other questions tagged c void-pointers or ask your own question .
- The Overflow Blog
- How to use marketing techniques to build a better resume
- How the creator of Angular is dehydrating the web (Ep. 574)
- Featured on Meta
- AI/ML Tool examples part 3 - Title-Drafting Assistant
- We are graduating the updated button styling for vote arrows
- Temporary policy: ChatGPT is banned
- Stack Overflow will be testing a title-drafting assistant, and we’d like your...
- We are graduating the "Related questions using Machine Learning" experiment
- The [connect] tag is being burninated
Hot Network Questions
- Meaning of "danach" in the following context
- What does the sentence "it's only dying a bit later than I would have, because I'm never going over to the Dark Side!" mean, especially its last part?
- What are the directories I see when I hit tab on `cd ~` that are not seen in `ls ~`
- Options for routing UF-B from exterior wall to interior load center
- Using a foreign passport in the UK as a British citizen
- How to convince management that not all software tools should be internally made?
- How many sorting networks?
- Is lying in an application for a job at a private company, signed under penalty of perjury, prosecutable as perjury?
- Player does crazy elaborate things, without the GM knowing where it will lead
- integer solutions of exponential equation
- How can I match the noise to a wavy pattern?
- Can you pack these tetracubes to form a rectangular block with at least one odd side length?
- Strange 3D Animal Movie Set in Venice?
- Did the Reformers accuse that the Catholic Church is "a pagan mixture"?
- Company wants to see offer letter received from another company to match salary
- Category of small categories is not adhesive?
- Why compass needle doesn't precess about but aligns by magnetic field?
- Does every USB device have a vendor id and product id?
- What is the order of the Great Hallel (Hallel HaGadol)?
- Are MD and MC both able to study both equilibrium and non-equilibrium systems?
- Does shield surfing on rails lower shield durability?
- Simple circuit works with BC547, but not with 2N3904
- "Solvitas perambulum": Is this real Latin?
- Are Borel sets whose projections are Borel closed under intersection?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Create Account
Home Posts Topics Members FAQ
Join Bytes to post your question to a community of 472,328 software developers and data experts.
Sign in to post your reply or Sign up for a free account.
Similar topics
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.

C++ Tutorial Index
C++ control statements, c++ functions, c++ strings, c++ inheritance, c++ polymorphism, c++ pointers, c++ exception handling, c++ constructors, c++ file handling, miscellaneous, c++ void pointer.
A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type.
Void Pointer Syntax:
We can't assign a variable's address to a variable of a different data type in C++.To better understand this let see an example below:
Explanation:
We define a pointer of type integer, ptr, and a float variable, 'i', in the preceding example. We try to save the address of 'i' variable in 'ptr' after declaration, but this is not feasible in C++ since the variable cannot carry the addresses of various data types.
Another example of a program containing void pointer in C++:
In the above program, we define an integer pointer and a float variable. An integer pointer variable cannot point to a float variable, but it can only point to an integer variable. The above problem was solved in C++ by utilizing the void pointer, which may contain the address of any data type.
We declare void pointer variable and integer variable in the preceding program, which contains the address of void pointer integer variable.
Advantages of Void Pointer in C++
- Because malloc() and calloc() return the void * type, they may be used to allocate memory of any data type (due to the void *).
- Normal functions in C are executed using void pointers. For example, in qsort, the compare function is used ().
Important fact: It is not possible to ignore void pointers. The following program, for example, does not compile.
Following program run fine with the compiler:
cppreference.com
Pointer declaration.
Declares a variable of a pointer or pointer-to-member type.
[ edit ] Syntax
A pointer declaration is any simple declaration whose declarator has the form
There are no pointers to references and there are no pointers to bit-fields . Typically, mentions of "pointers" without elaboration do not include pointers to (non-static) members.
[ edit ] Pointers
Every value of pointer type is one of the following:
- a pointer to an object or function (in which case the pointer is said to point to the object or function), or
- a pointer past the end of an object , or
- the null pointer value for that type, or
- an invalid pointer value .
A pointer that points to an object represents the address of the first byte in memory occupied by the object. A pointer past the end of an object represents the address of the first byte in memory after the end of the storage occupied by the object.
Note that two pointers that represent the same address may nonetheless have different values.
Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.
[ edit ] Pointers to objects
A pointer to object can be initialized with the return value of the address-of operator applied to any expression of object type, including another pointer type:
Pointers may appear as operands to the built-in indirection operator (unary operator * ), which returns the lvalue expression identifying the pointed-to object:
Pointers to class objects may also appear as the left-hand operands of the member access operators operator-> and operator->* .
Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:
Because of the derived-to-base implicit conversion for pointers, pointer to a base class can be initialized with the address of a derived class:
If Derived is polymorphic , such pointer may be used to make virtual function calls .
Certain addition, subtraction , increment, and decrement operators are defined for pointers to elements of arrays: such pointers satisfy the LegacyRandomAccessIterator requirements and allow the C++ library algorithms to work with raw arrays.
Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indexes of those elements, and pointers to non-static data members with the same member access compare in order of declaration of those members.
Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of std::less for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as std::set or std::map .
[ edit ] Pointers to void
Pointer to object of any type can be implicitly converted to pointer to void (optionally cv-qualified ); the pointer value is unchanged. The reverse conversion, which requires static_cast or explicit cast , yields the original pointer value:
If the original pointer is pointing to a base class subobject within an object of some polymorphic type, dynamic_cast may be used to obtain a void * that is pointing at the complete object of the most derived type.
Pointers to void have the same size, representation and alignment as pointers to char .
Pointers to void are used to pass objects of unknown type, which is common in C interfaces: std::malloc returns void * , std::qsort expects a user-provided callback that accepts two const void * arguments. pthread_create expects a user-provided callback that accepts and returns void * . In all cases, it is the caller's responsibility to cast the pointer to the correct type before use.
[ edit ] Pointers to functions
A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:
Unlike functions or references to functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, etc.
Note: declarations involving pointers to functions can often be simplified with type aliases:
A pointer to function can be used as the left-hand operand of the function call operator , this invokes the pointed-to function:
Dereferencing a function pointer yields the lvalue identifying the pointed-to function:
A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer (see address of an overloaded function for more detail):
Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).

[ edit ] Pointers to members
[ edit ] pointers to data members.
A pointer to non-static member object m which is a member of class C can be initialized with the expression & C :: m exactly. Expressions such as & ( C :: m ) or & m inside C 's member function do not form pointers to members.
Such pointer may be used as the right-hand operand of the pointer-to-member access operators operator. * and operator - > * :
Pointer to data member of an accessible unambiguous non-virtual base class can be implicitly converted to pointer to the same data member of a derived class:
Conversion in the opposite direction, from a pointer to data member of a derived class to a pointer to data member of an unambiguous non-virtual base class, is allowed with static_cast and explicit cast , even if the base class does not have that member (but the most-derived class does, when the pointer is used for access):
The pointed-to type of a pointer-to-member may be a pointer-to-member itself: pointers to members can be multilevel, and can be cv-qualified differently at every level. Mixed multi-level combinations of pointers and pointers-to-members are also allowed:
[ edit ] Pointers to member functions
A pointer to non-static member function f which is a member of class C can be initialized with the expression & C :: f exactly. Expressions such as & ( C :: f ) or & f inside C 's member function do not form pointers to member functions.
Such pointer may be used as the right-hand operand of the pointer-to-member access operators operator. * and operator - > * . The resulting expression can be used only as the left-hand operand of a function-call operator:
Pointer to member function of a base class can be implicitly converted to pointer to the same member function of a derived class:
Conversion in the opposite direction, from a pointer to member function of a derived class to a pointer to member function of an unambiguous non-virtual base class, is allowed with static_cast and explicit cast , even if the base class does not have that member function (but the most-derived class does, when the pointer is used for access):
Pointers to member functions may be used as callbacks or as function objects, often after applying std::mem_fn or std::bind :
[ edit ] Null pointers
Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (the behavior of dereferencing a null pointer is undefined), and compares equal to all pointers of the same type whose value is also null .
To initialize a pointer to null or to assign the null value to an existing pointer, the null pointer literal nullptr , the null pointer constant NULL , or the implicit conversion from the integer literal with value 0 may be used.
Zero- and value-initialization also initialize pointers to their null values.
Null pointers can be used to indicate the absence of an object (e.g. std::function::target() ), or as other error condition indicators (e.g. dynamic_cast ). In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, the delete expression does nothing when a null pointer is passed).
[ edit ] Constness
- If cv appears before * in the pointer declaration, it is part of decl-specifier-seq and applies to the pointed-to object.
- If cv appears after * in the pointer declaration, it is part of declarator and applies to the pointer that's being declared.
In general, implicit conversion from one multi-level pointer to another follows the rules described in qualification conversions and in pointer comparison operators .
[ edit ] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
[ edit ] See also
- Recent changes
- Offline version
- What links here
- Related changes
- Upload file
- Special pages
- Printable version
- Permanent link
- Page information
- In other languages
- This page was last modified on 19 May 2023, at 10:43.
- This page has been accessed 537,363 times.
- Privacy policy
- About cppreference.com
- Disclaimers


- Design Pattern
- Interview Q
C Control Statements
C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week


IMAGES
VIDEO
COMMENTS
a pointer to the first element of the array (type void * would be the most appropriate for that). a pointer to a comparison function that accepts pointers to array elements as arguments
The void pointer, at the same time noted because the particular common pointer, is actually the specific choice for pointer that will can easily become sharpened within items regarding any sort of knowledge type!
The assignment to the void pointer doesn't have any problem but the way you are trying to print the value using the pointer is incorrect. To need to cast the pointer to unsigned integer pointer and then access
A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. We can't assign a variable's address to a variable of a different data type in C++.To
A void pointer can point to a variable of any data type and void pointer can be assigned to a pointer of any type. We can't just dereference a void pointer using indirection ( *) operator
func2 takes a pointer to a constant character array as well as an integer and returns a pointer to a character, and is assigned to a C string handling function which returns a pointer to the first occurrence of a given character in a character array