在 C 中,不能将返回类型设为数组吗?我开始在我的操作系统课程中学习指针,我需要创建一个函数,该函数将 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() 方法中测试此函数?
我需要这样做的原因是因为我们正在学习进程和内存分配,并且指针在操作系统开发中起着重要作用。我的教授告诉我,指针很难理解,以至于许多编程语言都没有使用指针。