Is it valid to convert an array to a class/struct?

Asked

Viewed 30 times

0

Although I have tested I’m not sure if it will always work :

class Val {
public:
    int data[4];
};

int main() {
  int data[4];
  Val* v = reinterpret_cast<Val *>(data);
}
  • 1

    Why not simply assign it to the class member? What you are doing has undefined and unnecessary behavior. I don’t really like mixing C with C++,.

  • It’s just for fun. Let’s say I don’t have access to the/struct class (it’s in a library)

  • This doesn’t make sense, if it’s in the library you have access to, if it’s something private it’s better not to try to subvert anything, and if it’s in a library you don’t have access to, you don’t know how to make it work right, without information, without solution. What you’re asking is one thing, what you’re commenting on is another.

  • I just want to know whether or not there is access violation

1 answer

1


Rodrigo, the most guaranteed way to successfully convert array to structure is to create a structure constructor and an assignment operation. Thus, you determine how it is done and avoid problems. Also, whoever reads the code will know how the conversion occurs. Follow an example of code.

class Val {
    void __construct( int *dataArray ){
        data[0] = dataArray[0] ;
        data[1] = dataArray[1] ;
        data[2] = dataArray[2] ;
        data[3] = dataArray[3] ;
    }
    void __destruct( void ){
    }
public:
    int data[4] ;
    ~Val( void ){
        __destruct() ;
    }
    Val( int *dataArray ){
        __construct(dataArray) ;
    }
    Val& operator=( int *dataArray ){
        __destruct() ;
        __construct(dataArray) ;
        return *this ;
    }
} ;

int main() {
  int data[4] ;
  Val v1=data , v2 ;
  v2 = data ;
}

As to the reinterpret_cast, This is not data conversion but pointers to read the binary code of the data, reading as if it were data of another type. I have information that this works yes, it was as if you create a Union that deals pointer to int and pointer for structure composed of only type fields int, kind of.

union Pointer {
    int *dataPointer ;
    Val *valPointer ;
} ;

int main() {
    int data[4] ;
    Val *v ;
    /* v = reinterpret_cast<Val*>(data) ; */ {
        Pointer p ;
        p.dataPointer = data ;
        v = p.valPointer ;
    }
}

Any doubt?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.