如何在C编程中索引一组元素并返回一个索引数组



在我的程序中,我想找到数组suit中元素的索引,该索引等于1。IndexSuit函数将执行此操作,我希望从中返回一个数组,该数组是元素1的索引,例如{2,3,4,5,6}。

#include <stdio.h>
int * IndexSuit(int suitofdeck[], int suittype);
int main(int argc, char *argv[]) 
{
    int suit[13] = { 0,0,1,1,1,1,1,2,2,3,3,3,3 };
    int i;
    for (i = 0; i < 13; i++) {
        printf("%d", IndexSuit(suit, 1)[i]);
    }
}
int * IndexSuit(int suitofdeck[], int suittype) {
    int count = 0;
    int * index = calloc(13 ,13 * sizeof(int));
    int i;
    for (i = 0; i <= 13; i++) {
        if (suitofdeck[i] == suittype) {
            index[count] = i;
            count++;
        }
        return index;
    }
}

这里的问题似乎是你在哪里有回报。它在循环的一次迭代后返回。看起来应该在下面的直线上。

还有一些其他的改进,但我想建议。

1)你在main的循环中每次调用这个函数,这是分配内存,然后你从中选择一个值。我建议你调用它一次,然后遍历数组。

2)使用您当前的代码,没有办法区分索引值0和未分配的索引值(因为将有少于13个索引值,并且它们都被初始化为零)。我建议您返回实际设置的索引数。

我在这里做了一个稍微修改的版本:

#include <stdio.h>
#include <stdlib.h>
int * IndexSuit(int suitofdeck[], int suittype, int* numIndicies);
int main(int argc, char *argv[])
{
    int suit[13] = { 0,0,1,1,1,1,1,2,2,3,3,3,3 };
    int i;
    int* indicies;
    int numIndicies;
    indicies = IndexSuit(suit, 1, &numIndicies);
    for (i = 0; i < numIndicies; i++)
    {
        printf("%d ", indicies[i]);
    }
    printf("n");
    free(indicies);
}
int * IndexSuit(int suitofdeck[], int suittype, int* numIndicies)
{
    int count = 0;
    int * index = calloc(13 ,13 * sizeof(int));
    int i;
    for (i = 0; i <= 13; i++)
    {
        if(suitofdeck[i] == suittype)
        {
            index[count] = i;
            count++;
        }
    }
    *numIndicies = count;
    return index;
}

结果如下:

2 3 4 5 6 

最新更新