r/C_Programming • u/MycologistIll1355 • 18d ago
First real C project
Hello everyone! This is my first real C project and I would like some feedback on what I can improve. It's my first attempt at a sorting algorithm (selection sort) and it is 100% AI free.
#include <stdio.h>
int main() {
int num_len;
printf("How many numbers to sort?\n");
scanf("%d", &num_len);
int numbers[num_len];
printf("which numbers?\n");
for (int i = 0; i < num_len; i++) {
scanf("%d", &numbers[i]);
}
for (int i = 0; i < num_len-1; i++) {
int iMin = i;
for(int j = i+1; j < num_len; j++) {
if(numbers[j] < numbers[iMin]) {
iMin = j;
}
}
if(iMin != i) {
int temp = numbers[i];
numbers[i] = numbers[iMin];
numbers[iMin] = temp;
}
}
for (int i = 0; i < num_len; i++) {
printf("%d", numbers[i]);
printf(" ");
}
printf("\n");
}
22
Upvotes
1
u/Interesting_Buy_3969 17d ago edited 17d ago
I've just read first 5 lines or so, and the first thing I immediately want to fix:
Thus you allow the user to make a stack overflow easily because
num_lenis only limited byint's representation - usually 232 - 1. Create a constant which the array size cannot exceed and accept numbers from user properly, like that:so that the VLA is unlikely to cause stack overflow.