473,473 Members | 1,857 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Solved: C programming: confused by void *

131 New Member
I'm trying out void * types, but I'm not exactly sure how they work. If I wanted an int array with 10 elements, would it be declared as

Expand|Select|Wrap|Line Numbers
  1. void *int_p = (int *)malloc(sizeof(int) * 10);
  2.  
Here's where I'm lost; I've read not to cast malloc because malloc returns void * regardless. How then would malloc know what the type was?

How would I access the elements?

Expand|Select|Wrap|Line Numbers
  1. int i;
  2. for(i=0; i < 10; ++i) {
  3.    *(int *)(int_p + i) = i * 5 + i;
  4.    printf("%d", *(int *)(int_p + i));
  5. }
  6.  
I tried something like above without any warnings or errors, but is it correct? Any help would be greatly appreciated. Thank you in advance.
May 30 '12 #1
6 2136
Brian Connelly
103 New Member
Im not sure, but I think your first problem is understanding data types. Void is not a data type. Here is a start. http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx
May 30 '12 #2
divideby0
131 New Member
Thank you for the reply; I apologize for any confusion, by types, I meant converting to int, float, char, etc.

Expand|Select|Wrap|Line Numbers
  1. typedef struct {
  2.     void *data1;
  3.     void *data2;
  4.     void *data3;
  5. } void_ptrs;
  6.  
  7. void_ptrs test = { NULL, NULL, NULL };
  8.  
  9. test.data1 = malloc(sizeof(int));   // single int
  10. test.data2 = malloc(sizeof(float);  // single float
  11. test.data3 = malloc(100);           // char [100]
  12.  
  13. if(test.data1 && test.data2 && test.data3) {
  14.    *(int *)(test.data1) = 100;
  15.    *(float *)(test.data2) = 2.5;
  16.    strcpy((char *)test.data3, "testing");
  17.    ...
  18. }
That's the sort of thing I'm wanting to do, but I'm not sure if I'm doing it correctly.
May 30 '12 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
This code:
Expand|Select|Wrap|Line Numbers
  1. test.data1 = malloc(sizeof(int));   // single int
does not allocate an int. All it allocates is the size of an int. Since test.data1 is a void* all you have is an address.

To use it you would need to cast the pointer to the correct type and then you can use the memory for a variable of that type.

BUT: Since it's a void* you have lost the size of the allocation. Now you have no idea how much memory the allocation has and there is no way to find out.

So when you typecast the pointer to some type you have no idea of the allocation will hold a value of that type.

A void* is one of the biggest problem areas in C and is the reason you don't use these things in C++.
May 31 '12 #4
divideby0
131 New Member
eek; that doesn't sound good.

Thank you so much for the comments. I'm trying to learn the language on my own and this bit is bizarre.

Do you mean that the void* cannot be used by itself with malloc? I tried a few malloc variations using gcc 4 with warnings treated as errors.

Expand|Select|Wrap|Line Numbers
  1. void *test = NULL;
  2.  
  3. (int *)test = malloc(...) <- lvalue error
  4.  
  5. test = malloc(sizeof((int *)test); appeared ok
  6. *((int *)test) = 10;
  7.  
  8. test = malloc(sizeof(*((int *)test)); appeared ok
  9. *((int *)test) = 10;
  10.  
With the size being lost, wouldn't these have crashed?
May 31 '12 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
This code:
Expand|Select|Wrap|Line Numbers
  1. void *test = NULL;
  2.  
  3.   (int *)test = malloc(...) <- lvalue error
  4.  
won't compie because you are assigning a void* to an int*. You can assign an int* to a void* but not the other way around.

This code:
Expand|Select|Wrap|Line Numbers
  1. void *test = NULL;
  2.  
  3.  test = malloc(sizeof((int *)test); appeared ok
  4.  *((int *)test) = 10;
  5.  
You are allocating the size of an int address.

Then you assign the void* from malloc to a void* test. That's OK.

Then you cast a void* to an int*, dereference the int* and assign an int value. WARNING: You allocated the size of an address and not the size of an int. This works as long as the int value is the same size (or smaller) than an int address.

This code:
Expand|Select|Wrap|Line Numbers
  1. void *test = NULL;
  2.   test = malloc(sizeof(*((int *)test)); appeared ok
  3.   *((int *)test) = 10;
  4.  
allocates the size of an int. Then the void* from malloc is assigned to the void* test. That's OK.

Then the void* test is cast to an int*. That's OK.
Then the int* test is dereferenced to an int and an int value assigned. That's OK.

Just look at these things the way the compiler would look at it.
May 31 '12 #6
divideby0
131 New Member
Thank you so much for the detailed explanation - it really helped. I appreciate your time.
May 31 '12 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

21
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class...
34
by: Kishor | last post by:
Hi Friends Click here : www.c4swimmers.esmartguy.com to Test Your C Programming Strengths. You can find Tricky Questions on C, Interview type queries on C, Infrequently Answered Questions in C...
9
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; ...
134
by: evolnet.regular | last post by:
I've been utilising C for lots of small and a few medium-sized personal projects over the course of the past decade, and I've realised lately just how little progress it's made since then. I've...
9
by: vijay | last post by:
Hello, I am new to C Programming and just started reading K&R. I was about to finish the pointers chapter but got very confused with: 1. int arr; >From what I have read, arr is a pointer to...
12
by: Blaze | last post by:
I am doing the first walk through on the Visual Studio .Net walkthrough book to learn a little about programming. I am having issues with the first tutorial not running correctly. It seems that...
3
by: randomtalk | last post by:
hello everyone! Well, recently i've been trying to pick up c and see what is pointer all about (been programming in lisp/python for the better part of my last two years).. mmm.. I'm currently...
8
by: Lamefif | last post by:
// C3DRect supports IDraw and IShapeEdit. class C3DRect : public IDraw, public IShapeEdit { public: C3DRect(); virtual ~C3DRect(); // IDraw virtual void Draw(); // IShapeEdit virtual void...
10
by: Zero | last post by:
Hello all, I wonder about void? To which category in the C programming language does it belong? Of how many bits consits void? Is it possible to define a varibale called void a;
4
by: remember.sail | last post by:
is there a facility for void datatypes in c programming?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.