0

私はこのコードを持っています:

#include <stdio.h>

void sample(int b[3])
{
    //access the elements present in a[counter].
    for(int i=0;i<3;i++)
        printf("elements of a array are%d\n",b[i]);
}        

int main()
{
    int count =3;
    int a[count];
    int i;
    for(i=0;i<count;i++)
    {
        a[i]=4;
    }

    for(i=0;i<count;i++)
    {
        printf("array has %d\n",a[i]);
    }
    sample(//pass the array a[count]);

}

main()この関数のパラメーターとして渡すことにより、外部のユーザー定義関数でこのメイン関数で宣言された配列にアクセスしたいと思います。これどうやってするの?

4

5 に答える 5

2

通常、それを期待する関数は、配列の場所とサイズを知っている必要があります。これを行うには、配列の最初の要素へのポインターを渡します。

サンプル関数は次のようになります

void sample(int *b, size_t count) {
    for(int i = 0; i < count; i++) {
        printf("elements of a array are%d\n",b[i]);
    }  
}

最初の要素へのポインターを渡すことで配列を「渡す」ことができます。もちろん、配列の長さも渡すことができます。

sample(a, count);

配列が少なくとも 3 要素の長さになることが確実な場合は、count パラメーターを省略してこれを単純化することもできます。

于 2013-10-24T06:23:57.940 に答える
1
sample(a); //pass beginning address of array is same as sample(&a[0]);

関数宣言

  void sample(int b[]);

関数定義

  void sample(int b[]) // void sample(int *b)
  {  
      //access the elements present in a[counter].
      //You can access  array elements Here with the help of b[0],b[1],b[2]
      //any changes made to array b will reflect in array a
      //if you want to take SIZE into consideration either define as macro or else declare and define function with another parameter int size_array and From main pass size also 


  }
于 2013-10-24T06:20:20.737 に答える
0

配列は常に参照として渡されます。配列のアドレスを実パラメータに渡し、仮パラメータのポインタを使用してそれを受け入れる必要があります。以下のコードはあなたのために働くはずです。

void sample(int *b)     //pointer will store address of array.
{

     int i;
     for(i=0;i<3;i++)
         printf("elements of a array are%d\n",b[i]);
}        

int main()
{
    int count =3;
    int a[count];
    int i;
    for(i=0;i<count;i++)
{
    a[i]=4;
}

for(i=0;i<count;i++)
{
    printf("array has %d\n",a[i]);
}
sample(a);    //Name of array is address to 1st element of the array.

}
于 2013-10-24T10:59:45.273 に答える
0

完全な配列を関数に渡すには、ベースアドレス ie&a[0] とその長さを渡す必要があります。次のコードを使用できます。

#include<stdio.h>
#include<conio.h>
void sample(int *m,int n)
{
 int j;
 printf("\nElements of array are:");
 for(j=0;j<n;j++)
 printf("\n%d",*m);
}
int main()
{
int a[3];
int i;
for(i=0;i<3;i++);
{
   a[i]=4;
}
printf("\nArray has:");
for(i=0;i<3;i++)
{
    printf("\n%d",a[i]);
 }
sample(&a[0],3)
getch();
return 0;
}
于 2013-10-24T12:06:26.117 に答える
0

パラメータを次のように渡しますsample(a);

ただし、このコードは機能しません。変数を使用して配列のサイズとして渡すことはできません。

   #include<stdio.h>
   #define SIZE 3
   void sample(int b[]) {
      //access the elements present in a[counter] .
      for(int i=0;i<3;i++){
          printf("elements of a array are%d\n",b[i]);
      }        
   }

   int main() {
   int a[SIZE];
   int i;
   for(i=0;i<SIZE;i++){
       a[i]=4;
   }

   for(i=0;i<SIZE;i++){
       printf("array has %d\n",a[i]);
   }
   sample(a);
  }
于 2013-10-24T06:20:32.080 に答える