Hack Forums
[C] Dynamically cast through the sizeof(data_type) - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Dynamically cast through the sizeof(data_type) (/showthread.php?tid=5875864)



Dynamically cast through the sizeof(data_type) - aeiro - Aug 19, 2018

As you all may have noticed i'm trying to expand my knowledge of pointers.
Right now i'm working with void* and am using a macro defined as #define Make(x, y, z) (*((x*)(y)+z))

I've got a function that sets all the values in a struct to 0. works fine until i attempt this with a void*.

PHP Code

<?php 
void Instant
(int size, void* &prTest, int TypeSize) //TypeSize = sizeof(int) atm
{
 
 for (
int i = 0; i < size; i++)
 {
 
Make(char, prTest, i*TypeSize) = NULL; /////////Is there anyway i can cast this by the size of the type?
 
               //instead of creating a switch statement determining the value of type size and incrementing through the pointer by that type?
/*
 switch (TypeSize)
 {
 case sizeof(int) :
 Make(int, prTest, i) = NULL;
 }
*/
 
}
} 


I understand that Make(char, prTest, i*TypeSize) = NULL; will input 1 Byte into the address of prTest + i*TypeSize. I want to somehow fill Sizeof(Byte)*TypeSize





EDIT**

changed function to write everybyte
PHP Code

<?php 
void Instant
(int size, void* &prTest, int TypeSize) //TypeSize = sizeof(Struct)
{
    for (
int i = 0; i < size * TypeSize; i++)
        (
Make(char, prTest, i)) = NULL;
} 



RE: Dynamically cast through the sizeof(data_type) - Gorzoid - Aug 19, 2018

There is no 1 to 1 correspondence between type size and type. For example float and int will have the same size on most compilers. If your typesize is 4, how do you know if it should be a float or an int. If you just want to zero the memory, use memset(prTest, 0, size * TypeSize);
If you want to zero initialize the type, then you'll have to use enum switches or since you are using C++ and not C, use a template function


RE: Dynamically cast through the sizeof(data_type) - aeiro - Aug 19, 2018

(Aug 19, 2018 05:19 PM)Gorzoid Wrote:  There is no 1 to 1 correspondence between type size and type. For example float and int will have the same size on most compilers. If your typesize is 4, how do you know if it should be a float or an int. If you just want to zero the memory, use memset(prTest, 0, size TypeSize);
If you want to zero initialize the type, then you'll have to use enum switches or since you are using C++ and not C, use a template function

I'm trying to do everything manually to get a better understanding. but the function under EDIT**
does the same thing as memset. so that is what i'm sticking with.