I have an assignment where I have to create 3 arrays. The first two arrays have similar elements and the third is empty.
const int arraySize = 4;
array k[arraySize] = {1, 2 ,3, 7}
array j[arraySize] = { 1, 2, 8, 9}
array u;
int *ptr1 = arrayk;
int *ptr2 = arrayj;
How could I compare the elements in the first two and then copy over those duplicates to the third empty array (array u)?
I was thinking something like this:
for(int i = 0; i < arraySize; ++1) {
for(int k = 0; k < arraySize; ++k) {
if(&ptr1[i] == &ptr2[k]) {
//copy elements that are duplicates to array u
}
}
}
Since it looks like homework, I’m assuming you want to do it by yourself not by using a library to achive this. This being the case, your code is fine, you just have to keep an integer variable to store the next available position in u array.
This way, when you find a duplicate you assign it to the next available position on u and then increase the value of next by one.
Here is the pointer version, although I strongly recommend to avoid them in cases like this, and use them only when they are needed.