【问题标题】:How can index a group of elements and return back an array of index in C programming如何在 C 编程中索引一组元素并返回索引数组
【发布时间】:2015-10-12 06:33:34
【问题描述】:

在我的程序中,我想在数组 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;
    }
}

【问题讨论】:

  • 这段代码看起来并不遥远。你得到什么错误/输出?
  • 你在混合成语:做malloc(13 * sizeof(int))calloc(13, sizeof(int))。您分配的数量是您需要的 13 倍。
  • 您在循环内返回数组,这意味着您只捕获第一张卡片。您还需要一种方法来与调用者沟通索引数组的长度。
  • 非常感谢,我已经更正了。现在我可以在输出中得到 { 2,3,4,5,6,0,0,0,0,0,0,0,0}。顺便说一句,我怎样才能根据编号改变数组大小。我找到的元素。
  • 一个好的编译器会给你这个函数的警告。

标签: c arrays indexing


【解决方案1】:

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

虽然我想提出一些其他的改进建议。

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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2011-10-25
    • 2012-11-13
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    相关资源
    最近更新 更多