I wrote a program that sorts the values of an array. It has 5 arrays,
int arr1[] = { 3, 9, 6, 7 };
int arr2[] = { 2, 5, 5 };
int arr3[] = { 0 };
int arr4[] = { 1, 6 };
int arr5[] = { 4, 5, 6, 2, 1 };
and an array of pointers that holds those 5 arrays,
int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };
I want to sort the values of each array, but when I pass the arrays to the sorting function
sortArrValues(&pArr[i]);
it sees the first index of each array (arr1,arr2...) as the element of that array (pArr[i]), so pArr[i] is (3,2,0,1,4).
But I want pArr[i] to be the full array it meant to be, so in the first iteration pArr[i] will be (3,9,6,7).
Notes: the first index of each array indicates the length of that array (not including that index).
The sorting will skip the first index.
There are two additional functions,they're not used (you can skip them).
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 5
void sortArrValues(int** arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);
int main()
{
int arr1[] = { 3, 9, 6, 7 };
int arr2[] = { 2, 5, 5 };
int arr3[] = { 0 };
int arr4[] = { 1, 6 };
int arr5[] = { 4, 5, 6, 2, 1 };
int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };
int i = 0;
for (i = 0; i < LEN; i++)
{
sortArrValues(&pArr[i]);
}
//sortArrAdress(pArr);
//printArr(pArr);
return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int** arr)
{
int tmp = 0;
int i = 0;
for (i = 1; i < *arr; i++)
{
if (*arr[i] > *arr[i+1])
{
tmp = *arr[i];
*arr[i] = *arr[i + 1];
*arr[i + 1] = tmp;
}
}
}
*arr[i]->(*arr)[i]?i < *arrshould bei < **arr[]has a higher priority than*. So in order to force the derefence to occur first, you must wrap the dereference in parenthesis. Look up the operator precedence table, it will save your bacon when things are not making sense.