【发布时间】: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}。顺便说一句,我怎样才能根据编号改变数组大小。我找到的元素。
-
一个好的编译器会给你这个函数的警告。