我没有从选择排序算法中获取我的 (int) 数组的所有值

I don't get all the values of my (int) array from Selection Sort algorithm

我正在使用 gcc 编译器在 Ubuntu 14.04 上编程。

我正在使用 rand(); 函数为我的数组元素赋值。

( rand() % 101; 实际上,所以我得到的值不会高于 100 )

然后我想使用 'Selection sort' 算法对我的数组元素进行排序,但是当我打印(f)它们时,前两个元素是 0,即使我的数组中没有 0 (大部分时间)。

这是我的代码,请查看、编译、试用并指导我:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i, j, tam_arreglo;
    time_t t;
    int *a;
    int aux;
    /* Here I'm asking for you to give me the size of the array and store it in tam_arreglo */   
    printf("Introduzca el tamaño del arreglo: \n");
    scanf("%d",&tam_arreglo);

    /* Making my array the size I just asked you */
    int array[tam_arreglo];
    srand((unsigned) time(&t));
    /* Dynamic random filling of the array */
    printf("El arreglo sin ordenar es: \n");
    a = malloc(tam_arreglo * sizeof(int));
    for(i = 0 ; i < tam_arreglo ; i++) {
        a[i] = rand()%101;
        printf("%d\n", a[i]);
    }
    free(a);
    /* My 'Selection sort' algorithm */
    for(i = 0; i < tam_arreglo; i++) {
        for(j = i+1; j < tam_arreglo; j++) {
            if(a[i] > a[j]) {
                aux = a[i];
                a[i] = a[j];
                a[j] = aux;
            }
        }
    }
    /* Here's when I get the error, the first two elements printed are 0's */
    printf("El arreglo ordenado es: \n");
    for(i = 0; i < tam_arreglo; i++) {
        printf("%d\n", a[i]);
    }

    return(0);
}

我做错了什么?

你不应该 free() 数组,当你将不再访问指向的内存来购买指针时,你调用 free() 但从来没有。

当您在 free(a); 之后的代码中访问 a 指针时,将会出现垃圾,因为内存已经 free()

所以,在 return 之前的第二个 for 循环之后移动 free(a),它应该可以正常工作。

此外,您不需要在 return 中使用括号,并且在输入无效的情况下检查 scanf() 返回的值,因为在这种情况下 tam_arreglo 将未初始化,您的程序将调用未定义的行为。