-1

Hi I'm implementing bubblesort in C and got stuck with something that I couldn't figure out.

#include <stdio.h>
#include <time.h>
void main(){

    int i; 
    int j; 
    int vahe; 
    int sisse;
    int lst[50]; 


    printf("Enter how many elements you want to sort:");
    scanf("%d",&sisse); 

srand(time(NULL)); 
    for(i=0;i<sisse;i++){
        lst[i]=rand() % 1000; 

    }




    for(i=sisse-2;i>=0;i--){ 
        for(j=0;j<=i;j++){    
            if(lst[j]>lst[j+1]){ 
                vahe=lst[j]; 
                lst[j]=lst[j+1];
                lst[j+1]=vahe;
            }
        }
    }

    printf("Result: ");
    for(i=0;i<sisse;i++){
        printf("%d ",lst[i]);
    }




}

in this code i can give more than 50 elemnts to sort and it works for 53 elements. if I give 54 the last one isn't sorted. Why I'm able to do this and how to fix it so that i can only give in as much elements as the size of an array?

Ollikas
  • 199
  • 1
  • 3
  • 14

2 Answers2

1

This is because arrays work similar to pointers. In fact, an array variable is nothing more than an address pointing to a place in memory (the first element to be specific). Now if you do something like this: array[5], you are actually saying: Take the address that array points to and add 5 to it. At runtime, this will just be executed; the processor doesn't know that array is supposed to contain only (lets say) 4 elements. This is just important for the compiler, but afterwards, you have to take care about not exceeding the boundaries programmatically.

Why should you care when the program still works? Because the compiler expects that you will only store 4 elements in the array, and that you will do anything to make sure not more elements will be stored. Therefore, the compiler might use the memory below the 4th element and reserve it for another variable. When you now write beyond the array's boundaries, you would overwrite the value of said variable.

Philipp Murry
  • 1,660
  • 9
  • 13
0

If you access the array out of bounds, you are already in undefined behavior territory. You cannot reason with its behavior at that point.

R Sahu
  • 204,454
  • 14
  • 159
  • 270