Sunday, 3 April 2016

Ways of Passing Array from Function: C/C++ Brush up

In programming we make a call by two methods
1)call by value- Pass a value
2)call by reference - Pass a address and fun taking this address should have pointer.And also to                                            display result again pointer.

Array is passed to a function using Call be reference.

There is Two ways

1) Using &


  1. void main( )
  2. {
  3. int a[5]={1,2,3,4,5}
  4. for(int i=0 ; i<=4 ;i++)
  5.   {
  6. printarray(&a[0]);    //or printarray(&a);[NOT SURE]
  7.    }
  8. }
  9. .
  10. .
  11. .
  12. .
  13. void printarray(int *p)
  14. {
  15. printf("%d",*p);
  16. }

2) Without Using &


  1. void main( )
  2. {
  3. int a[5]={1,2,3,4,5}

  4. printarray(a);  
  5.    
  6. }
  7. .
  8. .
  9. .
  10. .
  11. void printarray(int *p)
  12. {
  13. for(int i=0 ; i<=4 ;i++)
  14.   {
  15. printf("%d",*p);
  16.    }
  17. }
  18. }

Passing Character Array through a Function
STRING IS THE ARRAY OF CHARACTER WITH ONE NULL '\O' CHARACTER IN THE END

There is 4 ways of initilizing a character

1) 

  1. char c[4];
  2. c[0]='j'; c[1]='o'; c[2]='h'; c[3]='n'; c[4]='\0';
2)

  1. c[ ]={'j','o','h','n','\0'}
3)Using String Literal

  1. c[ ]="john";
4) Using Pointer
  1. char*c="Hellow";

  1. int main( )
  2. {
  3. char *c="Hellow";
  4. print( c)
  5. .
  6. return(0);
  7. .
  8. }
  9. .
  10. .
  11. .
  12. .
  13. ..
  14. .
  15. void print(char *c)
  16. {
  17. int i=0;
  18. while( *(c+i)!= '\0') )
  19. {
  20. printf("%c",c[i]);
  21. i++;
  22. }
  23. printf("\n");
  24. }
  25. .
  26. .//or
  27. .
  28. .
  29. .
  30. .
  31. .
  32. void print(char *c)
  33. {
  34. while( *(c)!= '\0') )
  35. {
  36. printf("%c",c[i]);
  37. c++;
  38. }
  39. printf("\n");




Passing a 2-Dimentional Array through a Function

while passing two dimensional array to function last dimension is compulsory

  1. int func (int a[ ][3])
  2. {
  3. .
  4. .
  5. .
  6. .
  7. .}
Passing a 3-Dimentional Array


  1. int func (int a[ ][2][2])  / (int (*a)[2][2])
  2. {
  3. .
  4. .
  5. .
  6. .
  7. .}

No comments:

Post a Comment