In: Computer Science
Send an element from 2d array to a function using pointer to pointer. c++
I am having an issue with being able to send specific elements to the swap function.
#include <iostream>
using namespace std;
void swap(int **a, int **b){
int temp = **a;
**a=**b;
**b=temp;
}
void selSort(int **arr, int d){
for(int i =0; i<d-1; i++){
int min = *(*arr+i);
int minin = i;
for(int j =i+1; j<d; j++){
if(*(*arr+j)
< min){
min = *(*arr+j);
minin = j;
}
swap(*&(arr+i),*&(arr+minin));
}
}
}
int main() {
int array[2][2] = {4,3,2,1},
*ptr = &array[0][0],
**pptr = &ptr;
int size = sizeof(array)/sizeof(int);
for(int i =0; i<size; i++){
cout
<<*(*pptr+i)<<endl;
}
selSort(pptr, size);
for(int i =0; i<size; i++){
cout
<<*(*pptr+i)<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
void swap(int **a, int **b){
int temp = **a;
**a=**b;
**b=temp;
}
void selSort(int **arr, int d){
for(int i =0; i<d-1; i++){
int min = *(*arr+i);
int minin = i;
for(int j =i+1; j<d; j++){
if(*(*arr+j) < min){
min = *(*arr+j);
minin = j;
}
swap(*(*arr+i),*(*arr+minin));
// *arr derference value and add to min and then
*(*arr+i) is the address which is passed
}
}
}
int main() {
int array[2][2] = {4,3,2,1},
*ptr = &array[0][0],
**pptr = &ptr;
int size = sizeof(array)/sizeof(int);
cout<<"Before Sorting: \n"; // msg
you can also delete it if want
for(int i =0; i<size; i++){
cout <<*(*pptr+i)<<endl;
}
selSort(pptr, size);
cout <<"After Sorting: \n";
for(int i =0; i<size; i++){
cout <<*(*pptr+i)<<endl;
}
return 0;
}
/* OUTPUT */