Skip to content

Instantly share code, notes, and snippets.

@dumbbellcode
Created April 29, 2019 07:24
Show Gist options
  • Save dumbbellcode/a794bdafa7e742491a55687a1b472718 to your computer and use it in GitHub Desktop.
Save dumbbellcode/a794bdafa7e742491a55687a1b472718 to your computer and use it in GitHub Desktop.
Passing arrays to functions in c.
// Passing 1D array
#include <stdio.h>
void fun(int a[],int m) //Here a[] is actually a pointer .We can also use int* a instead of int a[],both are same.
{
for(int i=0;i<m;i++) {scanf("%d",&a[i]);}
}
void fu(int a[],int b[],int m)
{
for(int i=0;i<m;i++) {b[i]=a[i];}
for(int i=0;i<m;i++) {printf("%d ",b[i]);}
}
void main()
{ int a[10],b[10],m,n;
scanf("%d",&m); //Taking array size.
fun(a,m); // a (i.e a[]/*a) of fun () will now point to a[0] of main().
fu(a,b,m);
}
//Passing 2D array
#include <stdio.h>
void fun(int a[][10],int m,int n)//Here the second dimension of parameter array and passed argument array should be same.
{ //The argument is of type int(*)[10] so the parameter should be of int(*)[10]
for(int i=0;i<m;i++) //We cant use int*a[10] instead of int a[][10] because int *a[10] means array of 10 pointers
//but int a[][10] means array of pointers each pointing to array of 10 integers
{
for(int j=0;j<n;j++) {scanf("%d",&a[i][j]);}
}
}
void fu(int a[][10],int b[][10],int m,int n)
{ for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++) {b[i][j]=a[i][j];}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++) {printf("%d ",b[i][j]);}printf("\n");
}
}
void main()
{ int a[10][10],b[10][10],m,n;
scanf("%d %d",&m,&n);//Taking m rows n columns
fun(a,m,n);
fu(a,b,m,n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment