所以,我试图将一个函数中生成的数组调用到另一个函数中来处理它。现在,我环顾四周,我可以看到你无法调用整个数组,但可以调用它的指针。我不完全确定如何做到这一点,我的尝试让我失败了。
所以我来找你,这是我的代码到目前为止的样子(或者至少是我目前正在尝试使用的两个函数):
int CreatePermutation(int n){
int arr[25];
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
while(n<=0){
printf ("Please input a possitive number for a permutation size.\n");
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
}
for (int i=0; i<n; i++)
arr [i] = i+1;
return arr[25];
}
int main (){
int arr[25];
int n;
CreatePermutation(n);
for (int i=0; i<n; i++)
printf("%d", arr[i]);
}
当我尝试将CreatePermutation作为主函数来查看它是否有效时,它正在生成并正确打印排列,所以我真正需要的是将它放入主函数。
答案 0 :(得分:2)
您可以将数组作为参数传递:
int CreatePermutation(int *arr){
int n;
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
while(n<=0){
printf ("Please input a possitive number for a permutation size.\n");
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
}
for (int i=0; i<n; i++)
arr [i] = i+1;
return n;
}
int main (){
int arr[25];
int n;
n = CreatePermutation(arr);
for (int i=0; i<n; i++)
printf("%d", arr[i]);
return 0;
}
这样,您可以使用数组指针修改数组。您还可以在CreatePermutation
函数中返回排列的大小。
答案 1 :(得分:1)
我想你想要这样的东西:
int CreatePermutation(int n, int* arr)
{
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
while(n<=0){
printf ("Please input a possitive number for a permutation size.\n");
printf ("Please enter desired permutation size: ");
scanf ("%d", &n);
}
for (int i=0; i<n; i++)
arr [i] = i+1;
return arr[n-1];
}
int main (){
int arr[25];
int n = 25; /* Update thanks to PHIFounder */
CreatePermutation(n, arr);
for (int i=0; i<n; i++)
printf("%d", arr[i]);
}
答案 2 :(得分:0)
我将展示一个简单的例子,让事情更清楚,你可以从中获得线索并应用你的问题。
如果你愿意,你可以这样做:
#include <stdio.h>
int CreatePermutation(int arr[] , int n)
{
for ( int i = 0; i < n; i++)
arr [i] = i+1;
return arr[n-1];
}
int main ()
{
int arr[25];
int n ;
printf ("Please enter number of elements to be printed : ");
scanf ("%d", &n);//You should enter the number of elements before passing it to the function and in this way you can limit the number of elements you want to print .
CreatePermutation ( arr , n );
for (int i = 0; i < n; i++)
printf ("%d\n" , arr[i] );
}
注意 - 我的示例显示了一种根据您的意图传递数组的简单方法,您可以根据需要进一步调整它:)