简体   繁体   中英

How to move last element of array to the first element of another array in c programming

How can I move the last element of an array to the first element of another array if both of their sizes are 10. I need to remove the element from the first array and add it into the second array. And if the second array is full(has 10 elements) the element that was lost should be printed out like "Array 2 had no space, so element 5 was lost". Code:

char arr[10] = {1,2,3,4,5};
char arr2[10] = {6,7,8,9,10};

result:

arr[10]={1,2,3,4};
arr2[10]={5,6,7,8,9,10};

If the arr2 is full:

char arr[10] = {1,2,3,4,5};
char arr2[10] = {6,7,8,9,10,11,12,13,19,20};
'''
result:
"Array 2 had no space, so element 5 was lost"

If you want to achieve exactly what you describe, you'll have to shift all the elements of the array. This has a time complexity of O(n) - which is why arrays are usually not very good for this kind of a job.

You also have to store the number of elements that are actually present in the array. Since there isn't exactly another way to know that unless you use a terminating element.

char arr[10] = {1,2,3,4,5};
char arr2[10] = {6,7,8,9,10};
size_t arrlen = 5;
size_t arr2len = 5;
if (sizeof(arr2) == arr2len)
{
    printf("Element of value %d was lost\n", arr[arrlen - 1]);
    return;
}
// Increase the length of arr2
arr2len++;
// Shift the elements
for (size_t i = arr2len - 1; i > 0; --i)
{
    arr2[i] = arr2[i - 1];
}
// Set the new element
arr2[0] = arr[arrlen - 1];
// "Remove" the element from arr and decrement the length
arr[--arrlen] = 0;

Of course this is only a draft example - you should really really divide this into clean functions. Remember however, passing arrays to functions will decay them to pointers - in which case sizeof will not yield their full size, you'll have to pass that yourself.

Use a struct (containing the array) rather than the basic array.

struct arrayN {
    int arr[10];
    int N;
};

void last2first(struct arrayN *dst, struct arrayN *src) {
    // NEEDS VALIDATION, for the moment we can say that
    // it is UNDEFINED BEHAVIOUR calling last2first with bad data
    memmove(dst->arr + 1, dst->arr, 9 * sizeof *dst->arr);
    dst->arr[0] = src->arr[--src->N];
}

int main(void) {
    struct arrayN arr1 = {{1, 2, 3, 4}, 4};
    struct arrayN arr2 = {{42}, 1};

    last2first(&arr1, &arr2);
}

Note: both arr1 and arr2 always have 10 elements in their array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM