gpt4 book ai didi

c - 返回数组的函数(用 C 编写的 Win32 控制台应用程序,学习操作系统)

转载 作者:行者123 更新时间:2023-11-30 14:20:58 25 4
gpt4 key购买 nike

在C中,是否不能将返回类型设置为数组?我开始在操作系统类(class)中学习指针,我需要创建一个函数,该函数接受 2 个数组作为参数,并返回一个仅包含两个参数数组中的元素的数组。

这是我迄今为止返回数组的 C 函数:

#include <stdio.h>



main()
{
printf("Hello world");

int array1[4] = {1, 2, 3, 4};
int array2[4] = {3, 4, 5, 6};

int* inter = intersection(array1, array2);

printf(inter); // <-- also, I don't know how I could get this to work for testing


//freezes program so it doesn't terminate immediately upon running:
getchar();
}





int* intersection(int array1[], int array2[])
{
int arrayReturn[sizeof(array1) + sizeof(array2)];
int count = 0;

for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(array1[i]==array2[j])
{

arrayReturn[count] = array1[i];
count = count + 1;

}
}
}

return arrayReturn;
}

我的另一个问题是如何使用 printf() 语句在 main() 方法中测试此函数?

我需要这样做的原因是因为我们正在学习进程和内存分配,而指针在操作系统开发中发挥着重要作用。我的教授告诉我,指针非常难以理解,以至于许多编程语言都没有使用指针。

最佳答案

我们来了

#include <stdio.h>

/* declare function, you need to capture array size as well, and also allow
to get result target pointer, result space info and pointer to place where the
size of result will be captured */
int* intersection(int * array1, int a1len , int * array2, int a2len, int* result, int *resultsize, int resultspace);

main()
{
printf("Hello world\n");

int array1[4] = {1, 2, 3, 4};
int array2[4] = {3, 4, 5, 6};
int arrayr[32]; /*result will be in this table */
int resultsize;
int resultspace = 32;

int i;
/* here comes confusion - int resultsize means it will be read as integer,
so we need to write &resultsize to get the pointer,
array declaration like int arrayr[number] is actually understood by system
as a pointer to an integer, pointing to first element of array,
allowing you to use indexes
so arrayr[3] actually means *(arrayr + 3 * sizeof(int))
*/

int* inter = intersection(array1, 4, array2, 4, arrayr, &resultsize, resultspace);
/* inter is now a pointer to arrayr */
for (i = 0; i<resultsize; i=i+1) {
printf("%d\n", inter[i]);
}


//freezes program so it doesn't terminate immediately upon running:
getchar();
}





int* intersection(int * array1, int a1len , int * array2, int a2len, int* result, int *resultsize, int resultspace)
{
/* as we received a pointer to resultsize (*resultsize)
we need to de-reference it using "*" to get or set the actual value */

*resultsize = 0;

int i, j;
for(i = 0; i < a1len; i++)
{
for(j = 0; j < a2len; j++)
{
if(array1[i]==array2[j])
{

result[*resultsize] = array1[i];
*resultsize = *resultsize + 1;
if (resultspace == *resultsize)
return result;
}
}
}

return result;
}

关于c - 返回数组的函数(用 C 编写的 Win32 控制台应用程序,学习操作系统),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992329/

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