【问题标题】:I don't get all the values of my (int) array from Selection Sort algorithm我没有从选择排序算法中获得我的 (int) 数组的所有值
【发布时间】:2015-04-01 20:39:14
【问题描述】:

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

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

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

然后我想使用“选择排序”算法对数组的元素进行排序,但是当我打印(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);
}

我做错了什么?

【问题讨论】:

  • SO 不是用于代码审查的网站,而是用于提问的网站。
  • 你没有看到我的问题吗?

标签: c linux algorithm ubuntu selection-sort


【解决方案1】:

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

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

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

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

【讨论】:

  • 太谢谢你了,现在好像有魅力了,我怎么看不到呢,回复好快,还是要等你的答案标记为正确答案,再次感谢,你是大师!编辑:这里只是关于礼仪的问题,我现在应该编辑问题以显示正确答案吗?还是保持原样,将您的答案标记为正确答案?
猜你喜欢
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 2021-12-29
相关资源
最近更新 更多