ابزار کاربر

ابزار سایت


c-programming:pointers:arrays-as-function-arguments

Arrays as function arguments

/* arrays are always call by reference */
#include <stdio.h>
 
void f(int a[]) // implicitly converted to int *a
{
  printf("\n");
  printf("function: size of array : %d (worng)\n", sizeof(a));                      // 8
  printf("function: size of an element : %d\n", sizeof(a[0]));              // 4
  printf("function: number of elements : %d (wrong)\n", sizeof(a) / sizeof(a[0]));  // 2
}
 
int main()
{
  int a[] = {1, 2, 3, 4, 5};
 
  printf("\n");
  printf("main: size of array : %d\n", sizeof(a));                      // 20
  printf("main: size of an element : %d\n", sizeof(a[0]));              // 4
  printf("main: number of elements : %d\n", sizeof(a) / sizeof(a[0]));  // 5
 
  f(a);
 
  return 0;
}
/* arrays are always call by reference */
/* arrays convert to pointers when pass to functions as arguments */
#include <stdio.h>
 
void show(int a[], int s)
{
  int i;
  for(i=0; i<s; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");
}
 
void twice(int *a, int s)
{
  int i;
  for(i=0; i<s; i++) {
    a[i] *= 2;
  }
}
 
int sum(int a[], int s) // a is implicitly convert to pointer
{
  int sum = 0;
  int i;
  for(i=0; i<s; i++) {
    sum += *a;
    a++; // this was invalid if conversion did not take place
  }
  return sum;
}
 
int main()
{
  int a[] = {1, 2, 3, 4, 5};
  int total;
  int size = sizeof(a) / sizeof(a[0]);
 
  show(a, size);
  twice(a, size);
  show(a, size);
  total = sum(a, size);
  printf("total = %d\n", total);
 
  return 0;
}
c-programming/pointers/arrays-as-function-arguments.txt · آخرین ویرایش: 2024/04/19 17:55 توسط pejman

به جز مواردی که ذکر می‌شود، مابقی محتویات ویکی تحت مجوز زیر می‌باشند: Public Domain
Public Domain Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki