-
pointers with array
Here's my program.
Can anyone tell me how to use pointer points
to the data in ascending and other pointers
point to the data in descending, but keep the
original?
#include<stdio.h>
#include<stdlib.h>
#define SIZE 10
int *getNum(int *, int);
void selectSort(int *, int *);
void printSort (int *, int *);
int main(void)
{
int num[SIZE];
int *pLast;
pLast = getNum(num, SIZE);
selectSort(num, pLast);
printSort (num, pLast);
return 0;
}
/******************************* GET NUMBER *********************/
int *getNum(int *pNum, int size)
{
int readNum = 0;
int result, count = 1;
int *pFill = pNum;
do
{
printf("\nPlease enter number %d: ", count);
result = scanf("%d", pFill);
count++;
if(result == 1)
{
pFill++;
readNum++;
}
}while(result == 1 && readNum < size);
printf("\n\n");
return(--pFill);
}
/******************************* SELECT SORT *********************/
void selectSort(int *pNum, int *pLast)
{
int *smallest(int *pNum, int *pLast);
void swap(int *current, int *smallest);
int *pi, *pSmall;
for(pi = pNum; pi < pLast; pi++)
{
pSmall = smallest(pi, pLast);
swap(pi, pSmall);
}
return;
}
/*------------------------------ SMALLEST -----------------------*/
int *smallest(int *pNum, int *pLast)
{
int *pLooker, *pSmallest;
for(pSmallest = pNum, pLooker = pNum+1; pLooker <= pLast; pLooker++)
{
if(*pLooker < *pSmallest)
{
pSmallest = pLooker;
}
}
return(pSmallest);
}
/*------------------------------ SWAP -----------------------*/
void swap(int *p1, int *p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
return;
}
/******************************* PRINT DATA *********************/
void printSort(int *pNum, int *pLast)
{
int numPrint;
int *pPrint = pNum;
for(pPrint = pNum, numPrint = 0; pPrint <= pLast; numPrint++, pPrint++)
{
printf("%d ", *pPrint);
}
printf("\n\n");
return;
}
-
This sounds like a problem out of the C book I teach from!!
To things I see imediately:
printf("\nPlease enter number %d: ", count);
result = scanf("%d", pFill);
Watch how you enter numbers with pointers. you should change this line.
Second,
swap(pi, pSmall);
this call is wrong
Mr. C.