I am creating four functions:
- Allocate memory to an array
- Generate random chars an fill the array
- Sort the array into ascending order
- Print the sorted array
Like you will see in the code, I use a printf
to see the generated chars.
The problem is, that the sorting function is not working right and I can't understand where is the problem (I get an output where the characters aren't sorted like they should be).
Can someone please tell me what I'm doing wrong? Any other tips on how I can improve all the code would be welcome as well.
#include <stdio.h>
#include <stdlib.h>
int size = 20;
char* pArrChar1;
void allocate(char**);
void fill(char*);
void sort(char*);
void printArr(char*);
void main() {
allocate(&pArrChar1);
fill(pArrChar1);
sort(pArrChar1);
printArr(pArrChar1);
system("pause");
}
void allocate(char** p_char) {
*p_char = (char*)malloc(size*sizeof(char));
}
void fill(char* p_char) {
int max = 90 ;
int min = 65;
for (int i = 0; i < size; i++) {
p_char[i]= (char)(rand() % (min + 1 - max) + min);
printf("%c ", p_char[i]);
}
printf("\n\n");
}
void sort(char* p_char) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - 1; j++) {
if (*(p_char + j) > *(p_char + j + 1)) {
char tmp = *(p_char + j);
*(p_char + j) = *(p_char + j + 1);
*(p_char + j + 1) = tmp;
}
}
}
}
void printArr(char* p_char) {
for (int i = 0; i < size; i++)
printf("%c ", p_char[i]);
printf("\n\n");
}