Reputation: 21
I have a problem with my code. I'm trying to sort an array using pointers. The problem I'm having is that when the program is sorting the array, it doesn't process the last input element. I'm not so comfortable using pointers as of yet. I'd appreciate some feedback. Here's the code
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void inputarray(int *arr, int size);
void printarray(int *arr, int size);
void sortascending(int *arr, int size);
int main()
{
int array_size, array[MAX],choice;
printf("Enter size of array:\n");
scanf("%d",&array_size);
array_size -= 1;
printf("Enter elements:\n");
inputarray(array, array_size);
printf("Sorting scending:\n");
sortascending(array, array_size);
printarray(array, array_size);
return 0;
}
void inputarray(int *arr, int size)
{
int *arrayend = arr + size - 1;
while(arr <= arrayend)
{
scanf("%d\n",arr++);
}
}
void printarray(int *arr, int size)
{
int *arrayend = arr + size-1;
while(arr <= arrayend)
{
printf("%d", *(arr++));
}
}
void sortascending(int *arr, int size)
{
int *arrayend = arr + size - 1;
int i,j,t;
for(i=0; i< size; i++)
{
for(j=i+1; j< size; j++)
{
if(*(arr+j)<*(arr+i))
{
t = *(arr+i);
*(arr+i) = *(arr+j);
*(arr+j) = t;
}
}
}
}
So basically if I enter 5 elements in the order 9,8,7,6,5, it will return 6,7,8,9, neglecting the last input element (which is 5). Any tips?
Upvotes: 2
Views: 505
Reputation: 119
I see that after taking the array_size as input, you are decrementing it by 1, which is not necessary. This is because inside all your functions, you are doing arrend = arr + size - 1 i.e., you are doing arrend = arr[size-1]. This works when size is actual size of array. Hence you need not decrement array_size inside the main function. Working code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void inputarray(int *arr, int size);
void printarray(int *arr, int size);
void sortascending(int *arr, int size);
int main()
{
int array_size, array[MAX],choice;
printf("Enter size of array:\n");
scanf("%d",&array_size);
//no need to decrement size here
printf("Enter elements:\n");
inputarray(array, array_size);
printf("Sorting scending:\n");
sortascending(array, array_size);
printarray(array, array_size);
return 0;
}
void inputarray(int *arr, int size)
{
int *arrayend = arr + size - 1;
while(arr <= arrayend)
{
scanf("%d",arr++);
//remove \n from above line
}
}
void printarray(int *arr, int size)
{
int *arrayend = arr + size-1;
while(arr <= arrayend)
{
printf("%d", *(arr++));
}
}
void sortascending(int *arr, int size)
{
int *arrayend = arr + size - 1;
int i,j,t;
for(i=0; i< size; i++)
{
for(j=i+1; j< size; j++)
{
if(*(arr+j)<*(arr+i))
{
t = *(arr+i);
*(arr+i) = *(arr+j);
*(arr+j) = t;
}
}
}
}
Upvotes: 3