Mppl
Mppl

Reputation: 961

converting a void * to an array

I need to convert an array an place it in a struct that has a void* element and back to another array:

unsigned short array[size];
//do something to the array

typedef struct ck{

void * arg1;
void * arg2;
void * arg3;


} argCookie;


argCookie myCookie;

myCookie.arg2=malloc(sizeof(array));//alloc the necessary space
memcpy(myCookie.arg2,&array,sizeof(array));//copy the entire array there


//later....


unsigned short otherArray[size];
otherArray=*((unsigned short**)aCookie.arg2);

It happens that this last line won't compile... Why is that? obviously I've messed up somewhere...

Thank you.

Upvotes: 0

Views: 194

Answers (3)

Andriy
Andriy

Reputation: 8604

unsigned short* otherArray = (unsigned short*)aCookie.arg2

Then you can use otherArray[n] to access the elements. Beware of an out-of-bound index.

Upvotes: 0

nos
nos

Reputation: 229158

You can't copy arrays by assigning it a pointer, arrays are not pointers, and you cannot assign to an array, you can only assign to elements of an array.

You can use memcpy() to copy into your array:

//use array, or &array[0] in memcpy,
//&array is the wrong intent (though it'll likely not matter in this case
memcpy(myCookie.arg2,array,sizeof(array));

//later....

unsigned short otherArray[size];
memcpy(otherArray, myCookie.arg2, size);

That assumes you know size , otherwise you need to place the size in one of your cookies as well. Depending on what you need, you might not need to copy into otherArray, just use the data from the cookie directly:

unsigned short *tmp = aCookie.arg2;
//use `tmp` instead of otherArray.

Upvotes: 1

Daniel Fischer
Daniel Fischer

Reputation: 183918

You can't assign to arrays. Instead of

otherArray=*((unsigned short**)aCookie.arg2);

just use memcpy again, if you know the size:

memcpy(&otherArray, aCookie.arg2, size*sizeof(unsigned short));

If you don't know the size, you're out of luck.

Upvotes: 1

Related Questions