Pass by pointer - segmentation fault

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
}
}
 
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;
}
}

void psubtract_arr(int** arr1, int* arr2) {
for (int i=0; i<5; i++) {
(*arr1)-=arr2;
}
}

Fixed
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
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top