void* and memory allocation

I tried this code:
1
2
3
4
5
6
void *arr = new (int *)[num]; 

for (int x=0; x<num; x++)
  cin>>(int*)arr[x];

delete []arr;

but I get errors
what the problem ?
Last edited on
AFAIK, void pointer can only be used as a parameter or as a return value of a function...

CMIIW
You're trying to read something into a pointer (a temporary pointer, no less), which makes no sense (nor does any other part of the example).

AFAIK, void pointer can only be used as a parameter or as a return value of a function...
There's nothing (syntactically) wrong with the first line.
Of course you need a cast, however void pointers are not restricted to parameters or return values.
Last edited on

@Athar
There's nothing (syntactically) wrong with the first line.



I doubt that there is nothing wrong with the syntax of the first line.

@myoni

For what type of object are you trying to allocate the memory?
Last edited on
What I think you're trying to do is allocate a variable size array of ints and then enter a number into each entry in the array.

Try the following:
1
2
3
4
int * arr = new int[NUM]; 

for (int x=0; x<NUM; x++)
	cin>>arr[x];



Last edited on
I need to use void*, because It's need to be like template
to use in int, char, float etc...
vlad,
I need it for exercise
I need to use void*, because It's need to be like template
to use in int, char, float etc...

That's exactly the reason that templates take typenames as arguments.
http://www.cplusplus.com/doc/tutorial/templates/

1
2
3
4
5
6
7
8
9
10
template <typename T, int NUM> 
class mycontainer 
{ T * arr = new int[NUM]; 

  T * getInput ()
  {  for(it x=0; x<NUM; x++)
	cin>>arr[x];
      return arr;
  }
};


The actual type is supplied when the template is specialized:
mycontainer<int,5> five_ints;
 
T * arr = new int[NUM];


wasn't it should be:

 
T * arr = new T [NUM];


just my opinion (in other words, i'm not test it yet)
Topic archived. No new replies allowed.