C code for passing array to a function and returning pointer from function.
#include<stdio.h>
#include<stdlib.h>
void func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
printf("\nArray element after function : \n");
func(arr,5);//its a pass by reference only as name of the arry is the base address
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);//11 12 13 14 15
}
printf("\n");
return 0;
}
void func(int *p, int n)
{
int *arr=p;
int i;
for(i=0;i<n;i++)
{
arr[i]=p[i]+10;
}
}//end of main
Example 2:
/*
c code to pass array to a function
*/
#include<stdio.h>
#include<stdlib.h>
int* func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
int *p;
p=func(arr,5);
printf("\nArray element after function : \n");
for(i=0;i<5;i++)
{
printf("%d ",p[i]);//11,12,13,14,15
}
printf("\n");
return 0;
}
int* func(int *arr, int n)
{
int i;
int *p=arr;
p=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
p[i]=arr[i]+10;//arr[i] is must not p[i]
}
return p;
}
Example 3: not a good program
/*
c code to pass array to a function
*/
#include<stdio.h>
#include<stdlib.h>
int* func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
printf("\nArray element after function : \n");
func(arr,5);
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);//1 2 3 4 5
}
printf("\n");
return 0;
}
int* func(int *p, int n)
{
int *arr=p;
arr=(int *)malloc(n*sizeof(int));
int i;
for(i=0;i<n;i++)
{
arr[i]=arr[i]+10;//arr[i] is must not p[i]
}
return arr;/*if returning a pointer then function should have been called from a pointer */
}
#include<stdio.h>
#include<stdlib.h>
void func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
printf("\nArray element after function : \n");
func(arr,5);//its a pass by reference only as name of the arry is the base address
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);//11 12 13 14 15
}
printf("\n");
return 0;
}
void func(int *p, int n)
{
int *arr=p;
int i;
for(i=0;i<n;i++)
{
arr[i]=p[i]+10;
}
}//end of main
Example 2:
/*
c code to pass array to a function
*/
#include<stdio.h>
#include<stdlib.h>
int* func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
int *p;
p=func(arr,5);
printf("\nArray element after function : \n");
for(i=0;i<5;i++)
{
printf("%d ",p[i]);//11,12,13,14,15
}
printf("\n");
return 0;
}
int* func(int *arr, int n)
{
int i;
int *p=arr;
p=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
p[i]=arr[i]+10;//arr[i] is must not p[i]
}
return p;
}
Example 3: not a good program
/*
c code to pass array to a function
*/
#include<stdio.h>
#include<stdlib.h>
int* func(int *arr, int n);
int main()
{
int i;
int arr[]={1,2,3,4,5};
printf("\nArray element after function : \n");
func(arr,5);
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);//1 2 3 4 5
}
printf("\n");
return 0;
}
int* func(int *p, int n)
{
int *arr=p;
arr=(int *)malloc(n*sizeof(int));
int i;
for(i=0;i<n;i++)
{
arr[i]=arr[i]+10;//arr[i] is must not p[i]
}
return arr;/*if returning a pointer then function should have been called from a pointer */
}