L
LL
I want to demonstrate via this program pass by reference and pass by
pointer. But this program gives segmentation fault.
#include <stdio.h>
int a_[]={1,2,3,4,5};
int* a_ptr=a_;
int b[]={5,4,3,2,1};
// Passing ptr to array by reference
void subtract_arr(int*& arr1, int* arr2) {
for (int i=0; i<5; i++) {
arr1-=arr2;
}
}
// Passing by reference using pointers
void psubtract_arr(int** arr1, int* arr2) {
for (int i=0; i<5; i++) {
*arr1-=arr2;
}
}
main() {
subtract_arr(a_ptr,b);
for (int j=0; j<5; j++) {
printf("%d ", a_[j]);
}
psubtract_arr(&a_ptr,b);
for (int j=0; j<5; j++) {
printf("%d ", a_[j]); // Segmentation fault
}
}
pointer. But this program gives segmentation fault.
#include <stdio.h>
int a_[]={1,2,3,4,5};
int* a_ptr=a_;
int b[]={5,4,3,2,1};
// Passing ptr to array by reference
void subtract_arr(int*& arr1, int* arr2) {
for (int i=0; i<5; i++) {
arr1-=arr2;
}
}
// Passing by reference using pointers
void psubtract_arr(int** arr1, int* arr2) {
for (int i=0; i<5; i++) {
*arr1-=arr2;
}
}
main() {
subtract_arr(a_ptr,b);
for (int j=0; j<5; j++) {
printf("%d ", a_[j]);
}
psubtract_arr(&a_ptr,b);
for (int j=0; j<5; j++) {
printf("%d ", a_[j]); // Segmentation fault
}
}