C and C++

Moderators: None (Apply to moderate this forum)
Number of threads: 28691
Number of posts: 94711

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Determining the data type of a variable using pointers in C Posted by gofeddy on 15 May 2009 at 10:13 AM
How do you determine the data type of a variable using only pointers?
I mean, if you have 3 variables say:

int x
float y
char z

How do you determine the data type of these variables by accessing them using pointers?
Report
Re: Determining the data type of a variable using pointers in C Posted by anthrax11 on 15 May 2009 at 10:57 AM
Pointers have types associated with them:
int* px;
float* py;
char* pz;

If it's a void pointer, then it's not known which type it points to:
void* pv;

It's possible to analyse the variables by accessing them, but the methods you would use to do this depend on the specific problem.
Report
Re: Determining the data type of a variable using pointers in C Posted by gofeddy on 20 May 2009 at 2:22 PM
I got your point, but the question is, if I have 3 variables x, y and z, then how do I determine what data type they are of using pointers(no built-in functions)? Again, I assume I do not know what data type they are. How do I go about solving this?

An approach that I thought was, to use memory addressing(&), but I am not able to put it to use to solve this.
Report
Re: Determining the data type of a variable using pointers in C Posted by AsmGuru62 on 21 May 2009 at 4:52 AM
Just with a void* not possible. Only possible, if you create the structure for each variable and enclose the type inside it. But that would be completely different programming. Lots of overhead and unreadable.
enum VarTypes
{
	INTEGER = 1,
	FLOAT,
	DOUBLE,
	CHAR
};

typedef struct
{
	void* DataPtr;
	int SizeInBytes;
	int Type; // Values from VarTypes set
}
MYVAR;

int a = 9;
float b = 763.34f;
double c = 6327.9988737;
char s = 'A';

MYVAR var1 = { &a, sizeof (a), INTEGER };
MYVAR var2 = { &b, sizeof (b), FLOAT };
MYVAR var3 = { &c, sizeof (c), DOUBLE };
MYVAR var4 = { &s, sizeof (s), CHAR };

Now, you must pass var1...4 to every function to deal with variables. In short: BAD IDEA!
Report
Re: Determining the data type of a variable using pointers in C Posted by gofeddy on 21 May 2009 at 6:19 AM
Thanks for the info. It was helpful.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.