Home > Back-end >  Is there any way to copy address of every array's element address to another pointer array with
Is there any way to copy address of every array's element address to another pointer array with

Time:01-13

I am currently making a kind of 'controller' variable that can change the original variable's value.

It's for s/w logic that works like belows:

typedef struct PropertyA
{
    int* property1;
    int* property2;
    int* arr1[3];
} PropertyA

typedef struct PropertyB
{
    int* property2;
    int* property3;
    int* arr1[3];
    int* arr2[4];
} PropertyB

int main(int* property1,int* property2,int* property3,int arr1[], int arr2[])
{
// declare
PropertyA Controller1;
PropertyB Controller2;

// Initialize
Controller1.property1 = property1;
Controller1.property2 = property2;
//Copy all element's address from main func's argument 'arr1[]'

Controller2.property2 = property2; 
Controller2.property3 = property3;
//Copy all element's address from main func's argument 'arr1[]' and 'arr2[]' to Controller2.arr1,Controller2.arr2


// Main module 
Function1(Controller1); // this function changes property1, property2, arr1
Function2(Controller2); // this function changes property2, property3, arr1, arr2


return 0;
}

the main logic is divided by two functions, and each function changes the value by referencing address that Controller1 and Controller2 contains.

However, I think pointer array such as 'Controller1.arr1' should be initialized under for loop.

Is there any way like 'memcpy' to make the code simpler?

edit Question resolved. What I have misunderstood is that

  • to change the element of the array 'A' using pointer, I need to copy all of the address of the elements belong to 'A'

But it is desireable to

  • copy only the start address of array 'A' and change other elements by accessing the offset address.

So, what I need to do is just

  • simply change the strucutre's member variable(arr1[3], arr2[4]) from pointer array to a single pointer!

CodePudding user response:

As you have noted in the comments, controller serves no real purpose sinve you could pass arr and more simply index that arr[idx] where you currently have *arr[idx]. It seems to be an unnecessary level of indirection. In general though, there is no runtime non-iterative solution to generate an array of pointers to elements of an array (even if that made any kind of sense). You can statically initialise the array of course:

    int arr[3] = {3,4,5}; 
    int* controller[3] = {&arr[0], &arr[1], &arr[2]} ; 

But that would only be useful if the elements of controller were to be changed at runtime, (by sorting for example).

  • Related