Home > other >  getting extra value when printing out array
getting extra value when printing out array

Time:10-14

trying to print array in ascending order but i get extra value of 123261769 may i know why?

int selectionSort(int num[]){
    int sml;
    sml = 0;
    for (int i = 0; i < 5; i  ){
        for (int j = i 1; j < 5; j  )
        {
            if (num[i] > num[j]) 
            {
                sml = num[i];
                num[i] = num[j];
                num[j] = sml;
            }
        }
    }
        for (int k = 0; k < 5; k  )
        {
            printf("\n%i", num[k]);   
        }
}

int main(){
    int test[] = {5,3,2,1};
    int sortTest;
    sortTest = selectionSort(test);
    printf("%i",sortTest);
    return 0;
}

output

1 2 3 5 123261769

CodePudding user response:

Length of the array is 4, not 5.

int selectionSort(int num[]){
    int sml;
    sml = 0;
    for (int i = 0; i < 4; i  ){
        for (int j = i 1; j < 4; j  )
        {
            if (num[i] > num[j]) 
            {
                sml = num[i];
                num[i] = num[j];
                num[j] = sml;
            }
        }
    }
        for (int k = 0; k < 4; k  )
        {
            printf("\n%i", num[k]);   
        }
}

If you try to access the array element out of the bound you will get undefined behaviour. You might get different results on each run. when you try to access num[5], it will increment the initial address of the array by 5 (i.e num 5) and get whatever value is present on that memory location.

CodePudding user response:

your problem is that the array size is 4 not 5, so instead of editing all used places for this value, you can just use macros, so type at the top :

#define ARR_SIZE    4

and at any place, there is 5 mentioned, replace it with ARR_SIZE.

also in the function, selectionSort , the return type of this function is int but you didn't return anything (you didn't write return 0; for example at the end of the function).

with that said, this is the edited code:

#include <stdio.h>
#define ARR_SIZE    4
int selectionSort(int num[]){
    int sml;
    sml = 0;
    for (int i = 0; i < ARR_SIZE; i  ){
        for (int j = i 1; j < ARR_SIZE; j  )
        {
            if (num[i] > num[j])
            {
                sml = num[i];
                num[i] = num[j];
                num[j] = sml;
            }
        }
    }
    for (int k = 0; k < ARR_SIZE; k  )
    {
        printf("\n%i", num[k]);
    }
    return 1;
}

int main(){
    int test[] = {5,3,2,1};
    int sortTest;
    sortTest = selectionSort(test);
    printf("\nreturn value from the function : %i",sortTest);
    return 0;
}

and this is the output:

1
2
3
5
  •  Tags:  
  • c
  • Related