Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Pass by pointer - segmentation fault

0 views
Skip to first unread message

LL

unread,
Feb 28, 2009, 7:10:55 AM2/28/09
to
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[i]-=arr2[i];
}
}

// Passing by reference using pointers
void psubtract_arr(int** arr1, int* arr2) {
for (int i=0; i<5; i++) {
*arr1[i]-=arr2[i];
}
}

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

LL

unread,
Feb 28, 2009, 7:13:47 AM2/28/09
to
On Sat, 28 Feb 2009 12:10:55 +0000, LL wrote:

> 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[i]-=arr2[i];
> }
> }
>
> // Passing by reference using pointers void psubtract_arr(int** arr1,
> int* arr2) {
> for (int i=0; i<5; i++) {
> *arr1[i]-=arr2[i];
> }
> }
void psubtract_arr(int** arr1, int* arr2) {
for (int i=0; i<5; i++) {

(*arr1)[i]-=arr2[i];
}
}

Fixed

0 new messages