c - How to undo changes to an array after passing to a function -
c - How to undo changes to an array after passing to a function -
is there way undo actions or original array after changed array shown below.
#include <stdio.h> void function(int array[]){ array[2] = 20; //do work return; } int main(void){ int array[5] = {1,2,3,4,5}; function(array); // code has utilize original array homecoming 0; }
you can pack 2 32 bit integers (old / new) 64 bit integer, example:
#include <stdio.h> #include <stdint.h> void function(int64_t array[]) { array[2] = (array[2] << 32) | 20; } void printarr(int64_t array[], size_t n) { size_t i; (i = 0; < n; i++) { printf("%d ", (int32_t)(array[i])); } printf("\n"); } int main(void) { int64_t array[] = {1, 2, 3, 4, 5}; size_t i, n = sizeof(array) / sizeof(array[0]); function(array); puts("after function:"); printarr(array, n); (i = 0; < n; i++) { if (array[i] >> 32 != 0) /* changed */ array[i] = array[i] >> 32; /* undo */ } puts("original values:"); printarr(array, n); homecoming 0; }
output:
after function: 1 2 20 4 5 original values: 1 2 3 4 5
note:
of course of study can pack 2 16 bit integers in 32 bit integer if using short values in order save space.
to portable utilize prid32
format (defined in <inttyes.h>
) printf
, int32_t
:
printf("%"prid32" ", (int32_t)x);
another method:
if changes made sequentially on positive integers can alter sign (to identify change) , store changes using realloc
:
#include <stdio.h> #include <stdlib.h> typedef struct { int *value; size_t length; } t_undo; void function(t_undo *undo, int array[], int index, int value) { undo->value = realloc(undo->value, sizeof(int) * (undo->length + 1)); /* check realloc */ undo->value[undo->length++] = array[index]; array[index] = -value; } void printarr(int array[], size_t n) { size_t i; (i = 0; < n; i++) { printf("%d ", abs(array[i])); } printf("\n"); } int main(void) { t_undo *undo; int array[] = {1, 2, 3, 4, 5}; size_t i, j = 0, n = sizeof(array) / sizeof(array[0]); undo = malloc(sizeof(*undo)); /* check malloc */ undo->value = null; undo->length = 0; function(undo, array, 2, 20); puts("after function:"); printarr(array, n); (i = 0; < n; i++) { if (array[i] < 0) /* changed */ array[i] = undo->value[j++]; /* undo */ } puts("original values:"); printarr(array, n); free(undo->value); free(undo); homecoming 0; }
c arrays function
Comments
Post a Comment