【发布时间】:2019-01-14 10:33:57
【问题描述】:
我在 main 函数中取了一个数字,在 make_array 函数中把它变成一个数组。在palindrome 函数中,我需要检查我在make_array 函数中创建的数组,但它在palindrome 函数中不可见。
我该如何解决这个问题?
#include<stdio.h>
#define N 5
void make_array(int n);
int palindrome(int ar[],int size);
int main()
{
int num;
printf("Enter a number to check: ");scanf("%d",&num);
make_array(num);
if(palindrome(/*Don't know what should I write here*/))
printf("It is palindrome");
else
printf("It is not palindrome");
}
void make_array(int n)
{
int arr[N];
int digit,i=0;
while(n>0){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
}
int palindrome(int ar[],int size)
{
int i,j;
int temp[N];
j=N;
for(i=0; i<N; i++)
temp[i]=ar[i];
for(i=0; i<N; i++){
if(temp[j-1]!=ar[i])
return 0;
j--;
}
return 1;
}
【问题讨论】:
-
函数返回时局部变量消失。要么将数组传递给
make_array()函数,要么让它动态分配数组并返回指向它的指针。无论哪种方式都可以改变。 -
有几个问题,make_array 只是在栈上创建一个数组,当你离开函数时,它会从栈中弹出,不再存在。将你的数组从 make_array 移动到应用程序的全局,然后你可以在离开 make_array 后访问它。