LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - General
User Name
Password
Linux - General This 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


Reply
  Search this Thread
Old 03-06-2005, 06:38 PM   #1
aditya1
Member
 
Registered: Mar 2005
Location: College station, Texas
Distribution: UBUNTU 10.04
Posts: 61

Rep: Reputation: 15
what are void pointers used for?


I know what a void pointer is.But the problem is how to use it?When to use it?
 
Old 03-06-2005, 09:37 PM   #2
wapcaplet
LQ Guru
 
Registered: Feb 2003
Location: Colorado Springs, CO
Distribution: Gentoo
Posts: 2,018

Rep: Reputation: 48
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.
 
Old 03-07-2005, 03:28 AM   #3
aditya1
Member
 
Registered: Mar 2005
Location: College station, Texas
Distribution: UBUNTU 10.04
Posts: 61

Original Poster
Rep: Reputation: 15
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.
 
Old 03-07-2005, 05:14 AM   #4
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 51
This should probably be in the programming forum.

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.
 
Old 03-09-2005, 05:39 PM   #5
machron1
Member
 
Registered: Mar 2005
Posts: 34

Rep: Reputation: 15
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*.
 
Old 03-09-2005, 06:31 PM   #6
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 374Reputation: 374Reputation: 374Reputation: 374
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.
 
Old 03-09-2005, 08:19 PM   #7
machron1
Member
 
Registered: Mar 2005
Posts: 34

Rep: Reputation: 15
Quote:
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.

Last edited by machron1; 03-09-2005 at 08:21 PM.
 
Old 03-10-2005, 08:41 PM   #8
aditya1
Member
 
Registered: Mar 2005
Location: College station, Texas
Distribution: UBUNTU 10.04
Posts: 61

Original Poster
Rep: Reputation: 15
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)
 
Old 03-11-2005, 01:13 AM   #9
machron1
Member
 
Registered: Mar 2005
Posts: 34

Rep: Reputation: 15
Quote:
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;
}

Last edited by machron1; 03-11-2005 at 01:26 AM.
 
Old 03-11-2005, 02:02 AM   #10
machron1
Member
 
Registered: Mar 2005
Posts: 34

Rep: Reputation: 15
Quote:
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
 
Old 03-14-2005, 03:06 PM   #11
aditya1
Member
 
Registered: Mar 2005
Location: College station, Texas
Distribution: UBUNTU 10.04
Posts: 61

Original Poster
Rep: Reputation: 15
Smile

thanks to you all
all those suggestions were really valuable to me
and they were also useful.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
void pointers suchi_s Programming 9 11-08-2004 03:05 PM
void main(void) linuxanswer Programming 4 10-26-2003 12:37 AM
void? Patchorus Programming 9 10-25-2003 07:24 PM
void pointer help gonnaWorkItOut Programming 1 10-12-2003 11:52 AM
void foo(void) and void foo() lackluster Programming 9 02-15-2003 10:57 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - General

All times are GMT -5. The time now is 11:11 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration