//I want to revert array back to original state after 2nd printf statement OR code any other way such that next code a= (*p) operates on origianl array not on Update array.
CODE:
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[]={10,20,30,40,50};
int *p = arr;
int a;
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
a= *p;
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
//I WANT TO RESET ARRAY BACK TO ORIGINAL STATE after this printf statement or any other way such that next code a= (*p) operates on origianl array not on Update array.
a= (*p);
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
}
OUTPUT GIVEN:
arr[0] = 10, arr[1] = 20, a = 32767, *p = 10
arr[0] = 11, arr[1] = 20, a = 11, *p = 11
arr[0] = 12, arr[1] = 20, a = 12, *p = 12┌─[user@user]─[~/Documents/vs_code/DS/TEMP]
└──╼ $
OUTPUT EXPECTED:
arr[0] = 10, arr[1] = 20, a = 32767, *p = 10
arr[0] = 11, arr[1] = 20, a = 11, *p = 11
arr[0] = 11, arr[1] = 20, a = 11, *p = 11┌─[user@user]─[~/Documents/vs_code/DS/TEMP]
└──╼ $
CodePudding user response:
Stop writing C code and learn modern C .
You can use std::array
, which has value semantics. This allows you to simply copy the array and copy it back later if that is what you want:
#include <cstdio>
#include <cstdlib>
#include <array>
int main(){
std::array arr{10,20,30,40,50};
int *p = &arr[0];
int a = 0;
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
std::array arr2 = arr;
a= *p;
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
//I WANT TO RESET ARRAY BACK TO ORIGINAL STATE after this printf statement or any other way such that next code a= (*p) operates on origianl array not on Update array.
arr = arr2;
a= (*p);
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
}
Modifying the copy would have been better.
CodePudding user response:
Thanks for logic: @sam-varshavchik
Copy the original array values somewhere else, then copy them back when you're done fiddling with the array.
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[]={10,20,30,40,50};
int *p = arr;
int a;
int length= sizeof(arr)/sizeof(arr[0]);
int arr2[length];
for(int i=0; i<length;i ){
arr2[i]= arr[i];
}
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
a= *p;
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
p= &arr2;
a= (*p);
printf("\n arr[0] = %d, arr[1] = %d, a = %d, *p = %d", arr[0], arr[1],a , *p);
}