Reputation: 659
I have a function that looks like this:
void swapRows(int row_1, int row_2, double **matrix, int n, int m)
{
double arrTemp = (double *)malloc(m * sizeof(double));
int i;
for(i = 0; i < m; i++)
{
arrTemp[i] = matrix[row_1][i];
*matrix[row_1][i] = matrix[row_2][i];
}
for(i = 0; i < m; i++)
{
*matrix[row_2][i] = arrTemp[i];
}
}
I tried dereferencing the array using two stars and a single star but can not figure it out. I don't want to store it in another array and return it VIA a double function, I need to return it from this void function. I am just swapping rows in the array and need to return the modified array to the main function.
Upvotes: 0
Views: 275
Reputation: 11414
As long as you´re only changing the values in the array, you don´t need to do anything special. Remove all *
within the function and access the array like you don´t want to "return" it.
void swapRows(int row_1, int row_2, double **matrix, int n, int m){
double arrTemp = (double *)malloc(m * sizeof(double));
int i;
for(i = 0; i < m; i++){
arrTemp[i] = matrix[row_1][i];
matrix[row_1][i] = matrix[row_2][i]; //no *
}
for(i = 0; i < m; i++){
matrix[row_2][i] = arrTemp[i]; //no *
}
}
Unrelated problem, you´re missing a free to this malloc here.
And, as WhozCraig pointed out, in a double **matrix
where each row is allocated separately, you could just switch the row pointers.
void swapRows(int row_1, int row_2, double **matrix, int n, int m){
double *tmp = matrix[row_1];
matrix[row_1] = matrix[row_2];
matrix[row_2] = tmp;
}
Upvotes: 4