【问题标题】:passing whole 1-D array through a pointer to a function in C and then taking the array inputs through it通过指向 C 中函数的指针传递整个一维数组,然后通过它获取数组输入
【发布时间】:2021-10-16 01:52:04
【问题描述】:

在将指针传递给数组时,我遇到了一个大问题。请帮助我将指针传递给整个数组,然后将值传递给数组。

#include <stdio.h>
#include <stdlib.h>
void init(int **p,int n)
{
    printf("Enter the array elements:\n");
    for (int i = 0; i <n;i++) 
        scanf("%d",*p+i);
    
}
int main()
{
    int n;
    printf("enter the size of array\n");
    scanf("%d", &n);
    int a[n];
    init(&a,n);
}

I am getting this warning, but still its running when I run ./a.exe fie of it

【问题讨论】:

  • 我认为int a[n] 不会被编译。会报错。

标签: arrays function pointers


【解决方案1】:

代码的语法应该如下。

void fun(int *arr, int n)
{  
}
int main()
{
   fun(arr, n);
   return 0;
}

【讨论】:

    【解决方案2】:

    不可能声明动态长度的静态数组,比如int a[n]

    动态分配是解决方案。 最后别忘了发布它。

    试试这个。

    #include <stdio.h>
    #include <stdlib.h>
    void init(int *p,int n)
    {
        printf("Enter the array elements:\n");
        for (int i = 0; i <n;i++) 
        scanf("%d", p+i);
        
    }
    int main()
    {
        int n;
        printf("enter the size of array\n");
        scanf("%d", &n);
        int *a = new int[n];
        init(a,n);
        ...
        delete[] a;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2021-02-24
      • 2010-09-29
      • 2013-05-19
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多