Linux - GeneralThis Linux forum is for general Linux questions and discussion.
If it is Linux Related and doesn't seem to fit in any other forum then this is the place.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I've never really seen them used in C++, but in C I've seen them used for pointing to data that could be of any different data type. For instance, if you had several different kinds of struct, you could declare a (void *) that can point to any of them with the correct typecasting.
Honestly, though, 99% of the time you probably don't need them, and there is a better way to accomplish what you're trying to do. They require an explicit typecast, which can be unsafe, so it's usually best to avoid them if possible.
thank u,but actually the problem is that I was given a problem to design a text editor
using "void " pointers(a stack implementation).In this problem the text editor should accept the text entered from the user and store it in a file.While retrieving it from the file it should be able to distinguish between int ,char or any other symbols.
The only time I have EVER used a void pointer in C++ was when I needed to know if an object had just been created on the stack or on the heap. So I overloaded the objects operator new to push the void * returned by ::operator new onto a static list of void pointers, then in the constructor I checked if (void *)this was in my list, if it was I had a heap object else I had a stack object and I set my flag accordingly. It never worked right, but I can't remember the problem with it.
In C void * are used all over the place when a pointer doesn't always have the same type but you can figure it out yourself later.
The only time I ever used void* was in school during the term about creating generic data structures in C (stacks, linked lists, trees, etc.). The void* in each node of the data structure points to the contained data (whatever it may be). In C++ there isn't really a need for creating your own data structures with the advent of templates and the STL, and even in C there are enough pre-made libraries around to use. But if you are to make data structures in C to contain heterogenous data elements, there isn't a good way around using void*.
void *'s can be very useful, especially at the firmware level. Imagine reading/writing memory-mapped device registers. Some registers are a full 32 bits wide. Other registers are combinations of smaller values (like 4 8-bit values represeting status of different sections of the device). Sometimes reading/writing registers would have a side-effect (like pushing/popping an internal device FIFO/stack). In some situations you could read/write the whole 32 bits. In others, you would only want a single byte (because the other bits were linked to a side-effect register). So we were always typecasting the void *'s to char *'s, "unsigned16" *'s, or int *'s, based on the amount of data we could safely read or write to the device. Granted, we were also using the volatile keyword, but that's a whole other issue
Anyway, to address aditya's situation. My guess is, your teacher/professor/boss wants you to read the input file into a buffer in memory, and use a void * to store the buffer's location. Then probably go through the data, do some kind of analysis, determine what the data is (char sequence, int, or whatever), and then read it into variables of the appropriate type.
Originally posted by Dark_Helmet void *'s can be very useful, especially at the firmware level. Imagine reading/writing memory-mapped device registers. Some registers are a full 32 bits wide. Other registers are combinations of smaller values (like 4 8-bit values represeting status of different sections of the device). Sometimes reading/writing registers would have a side-effect (like pushing/popping an internal device FIFO/stack). In some situations you could read/write the whole 32 bits. In others, you would only want a single byte (because the other bits were linked to a side-effect register). So we were always typecasting the void *'s to char *'s, "unsigned16" *'s, or int *'s, based on the amount of data we could safely read or write to the device. Granted, we were also using the volatile keyword, but that's a whole other issue
Anyway, to address aditya's situation. My guess is, your teacher/professor/boss wants you to read the input file into a buffer in memory, and use a void * to store the buffer's location. Then probably go through the data, do some kind of analysis, determine what the data is (char sequence, int, or whatever), and then read it into variables of the appropriate type.
Obviously void* has its uses, however they appear to be almost exclusively in low-level C programming. I suppose the C++ OO methodology would be to have a class DeviceRegister and through inheritance, subclass this class for each type of register (ThirtyTwoBitRegister, FourEightBitComboRegister, ..., xxxRegister). As such, one may have both a homogenous collection of type <DeviceRegister> and a heterogenous collection containing one or more different types of DeviceRegister objects (that collection being one and the same). C++, although expensive, has a handy mechanism for identification of subclasses through Runtime Type Identification to keep downcasts safe. Further, I would imagine there would be a class (Singleton Pattern) possibly called RegisterManager which had a method called ReadRegister(...). It would read whatever register it was supposed to read according to its parameters, and return the resulting register information after it had been instantiated as the child register type and then up-cast to type DeviceRegister.
EDIT: And people think C and C++ programming are almost the same thing lol. You CAN use C++ the same as C, but it is like buying a Ferrari and only driving it 25mph.
thank you for your detailed response,I learned a lot 'bout
void pointers.Now I want to know the syntax of how
to take input into a variable using a void pointer.
and also the syntax of how to check whether
a variable is of char or int type while retrieving it from the file in which the data inputted were stored (of course using void pointers)
Originally posted by aditya1 thank you for your detailed response,I learned a lot 'bout
void pointers.Now I want to know the syntax of how
to take input into a variable using a void pointer.
and also the syntax of how to check whether
a variable is of char or int type while retrieving it from the file in which the data inputted were stored (of course using void pointers)
Just for you I decided to fire up KDevelop & spray some WD40 on my rusty C skills. I wrote a little sample program outling how to use void*. To answer your second questions, there is no good way to know what type of thing something is after it has been cast to void*. In C++ you can use RTTI (Runtime Type Identification) but I believe only when using inheritence.
Hope this code helps you:
Code:
/***************************************************************************
* Example of using void pointers (void*) *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
/* Array values */
#define ARRAY_SZ 3
#define I_NUMBER 0
#define S_WORDS 1
#define L_NUMBER 2
int main(int argc, char* argv[])
{
// Array of type void*
void* dataArray[ARRAY_SZ];
/* Various values to set the void pointers to in the array*/
int iNumber = 12;
char* sWords = "**This is a sentence**";
long lNumber = 123456L;
/* Assign the values above to the slots in the void* array */
dataArray[I_NUMBER] = (void*)(&iNumber);
dataArray[S_WORDS] = (void*)(sWords);
dataArray[L_NUMBER] = (void*)(&lNumber);
/* Intro Message */
printf("Hello, void* !\n");
/* Print dataArray[I_NUMBER] */
printf("The value of dataArray[I_NUMBER] is: %d\n", *(int*)(dataArray[I_NUMBER]));
/* Print dataArray[S_WORDS] */
printf("The value of dataArray[S_WORDS] is: %s\n", (char*)(dataArray[S_WORDS]));
/* Print dataArray[L_NUMBER] */
printf("The value of dataArray[L_NUMBER] is: %d\n", *(long*)(dataArray[L_NUMBER]));
return EXIT_SUCCESS;
}
Originally posted by aditya1 thank u,but actually the problem is that I was given a problem to design a text editor
using "void " pointers(a stack implementation).In this problem the text editor should accept the text entered from the user and store it in a file.While retrieving it from the file it should be able to distinguish between int ,char or any other symbols.
I just re-read this, and I think I can shine some light on what you are trying to accomplish (maybe?).
1) OK, first thing's first: Designing a stack in C cannot take advantage of C++ templates, so that's the only reason you will use void pointers. It's the only way to make a generic reusable collection. However, in your implementation, you are probably going to only store one type of object in it (char most likely).
2) The stack will probably be implemented as a dynamically linked list (probably only singly linked). top() will return the value (as void*) of the head of the list. pop() will return the value of the head of the list, and remove the head of the list. push() will place a new Node on top of the old head and the new Node will be the new head. You might also implemented other convenience functions such as size(). I don't know how "Object Oriented" you are trying to get with C, but more than likely you will have simply a set of functions that know how to manipulate some Node structs, where each Node has knowledge of next element (except of course the tail Node, it has no next element, and that's normally how you know it's the tail).
3)
Your stack I believe will be acting as a buffer. Considering your buffer will be a stack, I suppose it will be the most simple editor possible, i.e. a line editor with no random access (if you mess up, you have to delete, no going back and changing a letter that isn't on top of the stack). Writing to the file means popping one-by-one chars off the stack and writing them to the file. Since a stack is a LIFO collection, this might present a challenge depending on how and when you must write things to file. So long as writing to file is an all-or-nothing proposition, it should be straight forward. If there is any sort of intermediate file writing, you might have some jumbled files
4) This is where I think you are the most confused (or I'm confused, one or the other). You will not be examining void* objects and determining what data type they are, they will all be the same type (probably char data types). What you MAY do is examine the ascii value of the char to determine whether it is a letter, number, or special character. Using the ascii value is basically the only way you can tell what something is. If necessary (which I can't imagine why it would be in a text editor, but this is a homework assignment so anything goes) you can simply do an ascii comparison test on an individual char. Something like bool isANumber(char c){return (c >= '0' && c <= '9');} There are also some conversion and formatting functions in C to help conversion between char and int, etc once you test & determine what you are dealing with.
Hope that helps, and if/when you start to program in C/C++ and the STL, or Java (like me) you will really appreciate how many shortcuts you get to use once you've learned all the low-level things like this
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.