gpt4 book ai didi

c - 在 C 函数中拆分一个 int 数组并返回 2 个不同的数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:57 27 4
gpt4 key购买 nike

我尝试拆分一个 int 数组。该数组包含正数和负数,我希望该函数返回 2 个数组,一个为正数,一个为负数。

我已经尝试了以下代码,但它没有按预期工作。

 int main(void)
{
int array[] = {1, -1, 2, 3, 4, -5, 6};
int cnt = sizeof(array)/sizeof(array[0]);
int *neg, *pos;
int **low = &neg;
int **high = &pos;

neg = (int*) malloc(sizeof(int) * 2);
pos = (int*) malloc(sizeof(int) * 5);

sort(array, cnt, low, high);

for(int i = 0; i < 5; i++)
{
printf("%3d\n", pos[i]);
}

//same for negative array

return 0;

}

int sort(int *arr, int cnt, int **low, int **high)
{
for(int i = 0; i < cnt; i++)
{
if(arr[i] > 0)
{
*high[0] = arr[i];
**high++;
}
else
{
*low[0] = arr[i];
**low++;
}
}
}

如果有人能告诉我我做错了什么会很有帮助。

最佳答案

如评论中所述,int** 的双重间接寻址是不必要的。更合适的函数接口(interface)如下所示。它以数组和计数作为输入,以及指向足够大的输出数组的指针。作为输出,数组中填充了正(负)值,每个数组的计数写入*npos (*nneg)。

零的处理留给你。只需编辑 if 条件。

另请注意我如何使用 *npos += 1 而不是 (*npos)++ 来避免运算符优先级错误。

void separate(int *arr, int cnt, int *neg, int *pos, int *nneg, int *npos)
{
*nneg = 0;
*npos = 0;

for(int i = 0; i < cnt; i++)
{
if (arr[i] > 0)
{
pos[*npos] = arr[i];
*npos += 1;
}
else if (arr[i] < 0)
{
neg[*nneg] = arr[i];
*nneg += 1;
}
}
}

虽然在您的示例中您知道有多少正值和负值,但通常您应该分配绝对足够大的数组,即 cnt 元素。

关于c - 在 C 函数中拆分一个 int 数组并返回 2 个不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57060340/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com