c - 如何将数组传递给 C 中的函数

标签 c arrays function

我在 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;

}

最佳答案

最好的方法是将分配留给调用者。然后你可以简单地做

int main()
{
    int num;
    printf("Enter a number to check: ");scanf("%d",&num);

    int array[num];

    fill_array(num, array);

fill_array 在您的代码中执行“make_array”执行的操作,减去分配部分。

void fill_array(int num, int array[num]);

可以类似地重写回文函数:

int palindrome(int size, int array[size])

所有这些都使用了可变长度数组 (VLA) 的概念。

关于c - 如何将数组传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179765/

相关文章:

c - 将 bash 命令 echo 和 bc 管道化到 C 程序中

c++ - 在函数返回后释放动态分配的结构数组。

C - 如何从 stdin 正确读取本地化输入?

java - 计算字符串中的单词数

c - Strlwr 函数 - 在 xcode 9.2 中出现错误

javascript - 在 javascript(或 jQuery)中使用变量触发同名函数

c - 为什么我的输出在 fgets 中自动格式化,即 '\n'?

javascript - 如何从两个异步函数中获取变量的值

javascript - 列表项数组上的 Onclick 事件

c++ - 可变参数函数 va_arg() 返回不正确的参数