1

I'm trying to copy the data present in an array of pointers to another one.

I have very few knowledge in C++, but some in higher level languages.

Here is a sample code of what I've achieved so far (simplified version):

#define MAX_ACTIVE_MODES 3

myStruct_t priorities1[MAX_ACTIVE_MODES];

myStruct_t *priorities2[MAX_ACTIVE_MODES];

for (unsigned short i = 0; i < MAX_ACTIVE_MODES; ++i) {
   priorities2[i] = (myStruct_t*)malloc(sizeof(myStruct_t));

   memcpy(priorities2[i], &priorities1[i], sizeof(myStruct_t));
}

// ...

delete[] *priorities2;

It's easier for me to have a non pointer var for priorities1 and have one for priorities2 because I'm passing it to a sort function.

When I search for solutions, there's never the case of type *var[] and I don't get why.

8
  • 1
    What's working and what is not ? Except the delete, this really is C style code, why not use C++ std::array ? Commented Jan 11, 2020 at 21:24
  • You do something strange in delete[] priorities; and priorities2[i] = (myStruct_t)malloc(sizeof(myStruct_t)); use new in C++ Commented Jan 11, 2020 at 21:32
  • 1
    @Andrey, No! never use new in c++. Use smart pointers or container classes instead. Commented Jan 11, 2020 at 21:38
  • @HAL9000 yes, use RAII, but in education task new is way to learn pointers and mem alloc Commented Jan 11, 2020 at 21:40
  • 1
    @Andrey, When learning about pointers and mem alloc, I agree, you are forced to use new / malloc. But any recomendation to use new must come with a warning, Only for educational purpose Commented Jan 11, 2020 at 21:51

1 Answer 1

1

Even though your question is tagged , I assume that you are programming in C based on your use of malloc.

First you don't need to use memcpy to copy structs.

*priorities2[i] = priorities1[i];

should be equivalent to

memcpy(priorities2[i], &priorities1[i], sizeof(myStruct_t));

Second, you don't have to create copies of the elements in priorities1[]. Just have the pointers in priorities2[] point to the elements in priorities1[]:

for (size_t i = 0; i < MAX_ACTIVE_MODES; ++i) 
  {
     priorities2[i] = &priorities1[i];
  }

As long as you don't access priorities2 beyond the lifetime of priorities1, no malloc or free is needed.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reply. The thing is I'm making a copy because I don't want the original struct to be modified if I make changes in the copied one. So it's not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.