基本排序功能,难以正确初始化我的数组

时间:2016-11-08 02:42:31

标签: c gdb

我试图创建一个简单的应用程序,该应用程序从stdin获取一个数字列表,并通过将所有变量转换为' semi'来对它们进行排序。通过采用简单的数字平均值并将它们分成两个数组来对列表进行排序:

(a[] is <= avg)
(b[] is > avg)

我的计划是对我的两个列表进行排序,然后合并它们。 (我也明白,我通过这项工作获得的任何优化都很可能因为不保持简单而丢失)。

这是我的代码,我将跟进以下两个问题:

#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>

bool compare(val1,val2)
{
    if(val1 > val2){return false;}
    else{return true;}
}

int average(char *array[],int count)
{
    int total = 0;
    for(int i=1;i<count;i++){
        int temp = atoi(array[i]);
        total = temp+total;
    }
    int avg = total/(count-1);
    return avg;    

}

int main(int argc, char *argv[])
{
    //produce average for argv array excluding *argv[0]
    int avg = average(argv,argc);
    for(int i=1; i<argc; i++){
        //print unsorted list for debugging
        //TODO remove this
        printf("%s\n",argv[i]);
    }

    //setup int arrays (-2 because argc = count +1 & because of average one number will always be > or < average.
    int a[argc-2];
    int b[argc-2];
    //start counters for a=below avg b =above avg
    int acount = 0; 
    int bcount = 0;

    //cycle through argv[i] and cast values to new arrays a && b
    for(int i=1; i<argc; i++){
        //temp variable to avoid excessive atoi()
        int temp = atoi(argv[i]);
        if(temp <= avg){
            a[acount] = temp;
            acount++;
        }
        else{
            b[bcount] = temp;
            bcount++;        
        }
        //print temp for debugging
        //TODO remove this.
        printf("%d\n",temp);            
    }
    // sort a
    for(int i = 1; i <acount; i++){
        int temp;
        if(compare(a[i],a[i+1])){}
        else{
           temp = a[i];
           a[i] = a[i+1];
           a[i+1] = temp;   
        }
        printf("\n%d\n",a[i]);
    }


    return 0;
}
  1. 我在尝试调试代码时遇到了困难。我正在努力 打破printf("\n%d\n",a[i]);并运行以下内容 这些结果:

    (gdb) b 69
    (gdb) r 1 2 3
    Breakpoint 1, main (argc=4, argv=0xbffff184) at work.c:69
    69          printf("\n%d\n",a[i]);
    (gdb) info locals
    temp = 2
    i = 1
    avg = 2
    acount = 2
    bcount = 1
    b = <optimized out>
    (gdb) p a[i]
    No symbol "a" in current context.
    (gdb) p *argv[i]
    $1 = 49 '1'
    
  2. 我在这里做错了什么a[]b[]并没有像我希望的那样存储价值?

0 个答案:

没有答案