Accessing an array present in main in a function - c

I have this code:
#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]);
}
I want to access the array declared in this main function in a user defined function outside main() by passing it as parameter of this function. How can I do this?

The function expecting it usually has to know where the array is and the size of it. To do that, you'd pass a pointer to the first element of the array.
Your sample function could look like
void sample(int *b, size_t count) {
for(int i = 0; i < count; i++) {
printf("elements of a array are%d\n",b[i]);
}
}
You can 'pass' the array by passing a pointer to its first element and of course, also pass the length of the array.
sample(a, count);
You could also simplify this by omitting the count parameter if you can be sure the array will be at least 3 element long.

sample(a); //pass beginning address of array is same as sample(&a[0]);
Function declaration
void sample(int b[]);
Function definition
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
}

pass the parameter as sample(a);
However this code will not work. You cannot use a variable to pass as size of array.
#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);
}

Arrays are always passed as reference. You need to pass address of array to actual parameters and accept it using pointer in formal parameter. Below code should work for you.
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.
}

To pass a complete array to a function you need to pass its base address i.e.&a[0] and its length. You can use the following code:
#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;
}

Related

Sum of Arrays and Pointers with Functions

I have 2 arrays. I read them trough a function. Then I sum them trough another function and print the sum array trough another function. I have to use pointers all the time. Problem is, it prints the sum of the last two elements of the array as the whole sum array. How can I fix this?
#include<stdio.h>
void read(int *pdato);
void print(int *pdato);
void sum(int *pdato1,int *pdato2, int *pdato);
int main(){
int A[5],B[5],C[5],i;
printf("Data for first array:\n");
read(A);
printf("Data for the second array\n");
read(B);
sum(A,B,C);
printf("Result:\n");
print(C);
return 0;
}
void read(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:",i);
scanf("%d",pdato);
}
}
void sum(int *A,int *B, int *C){
int i;
for(i=0;i<5;i++){
*(C+i)=*(A+i)+*(B+i);
}
}
void print(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:%d\n",i,*pdato);
}
}
Should be
printf("[%d]:%d\n",i,pdato[i]);
and
scanf("%d",&pdato[i]);
Building off of #Massey101, here is the answer without using array notation:
Should be
printf("[%d]:%d\n",i,*(pdato + i));
and
scanf("%d",pdato + i);
Another solution is below. Increment pointer after every data read to point to correct memory location to store inputs.
for(i=0;i<5;i++) {
scanf("%d",pdato);
pdato++;
}
Increment pointer while printing results, so that it will fetch results from correct memory location as show below
for(i=0;i<5;i++) {
printf("[%d]:%d\n",i,*pdato);
pdato++;
}

dought in returning array and int data type from function in c

code 1
main()
{
int i ,a[5];
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
yo(a);
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
}
void yo(int a[5])
{
int i;
for(i=0;i<5;i++)
{
a[i]=a[i]+1;
}
}
in the above code with out returning values(i am returning void data type in function) the array 'a' is getting updated in main function but when i don't use array and use normal int data type the values does'nt get updated see code 2
main()
{
int a;
a=50;
yo(a);
printf("%d",a);
}
void yo(int z)
{
z=150;
}
It is because the array a[] is being passed as a pointer, not a copy of the array, and the array is modified directly. If you declare the function as
void yo(int *a)
that will work in exactly the same way. But if you pass a single int such as
void yo(int a) {
a += 1;
}
the function only receives a copy of the int and it does not affect the caller. To affect the variable passed, you would have
void yo(int *a) {
*a += 1;
}
And guess what? That's the same declaration as I put earlier when you pass an array. When you pass a pointer, it can be treated as an array, or as a single value - namely an array of length 1.

passing 2d array to function with in c

Is there any way to pass 2D array to a function as function(arr,m,n)
and the function defenition as void function(int **p,int m,int n)
ie, Without explicitly specifying array size ??
Let us C has a good explanation about how to pass two D array as parameter.
I usually use these two ways for passing 2D array as parameter. But you need to specify the size explicitly.
void display1(int q[][4],int row,int col){
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",q[i][j]);
printf("\n");
}
}
void display2(int (*q)[4],int row,int col){
int i,j;
int *p;
for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
}
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,0,1,6};
display1(a,3,4);
display2(a,3,4);
}

Function which receives a 1 d array and print its value there?

I wanted to write a function which can receive a 1-D array and print its value there.Also wanted to know how 2-D array can be received by a function and print its value there.
In C you pass arrays by pointers, and usually a second parameter, which contains its length.
For Example: void printArray(char * arrayStart, int length) (for a char array)
and I assume you know how to write a simple for-loop to iterate over all elements of your array and print them. For 2D Arrays you would use char ** arrayStartinstead.
(When calling the function you pass the array in the following fashion:
char myArray[] = "some Text"
printArray(myArray, 9);
)
sample code here:
#include<stdio.h>
void print_1D(int *arr,int m)
{
int i;
for(i=0;i<m;i++)
printf("%d ",arr[i]);
putchar('\n');
}
void print_2D(int *arr[num],int m,int n) //<---observe here
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",arr[i][j]);
putchar('\n');
}
}
int main()
{
int oneD[anySize1] = {2,5,67,23,32,....};
int twoD[anySize2][num] = { {23,17,..},{....},{....},....}; //<---and here
int m = anySize1,n = anySize2;
print_1D(oneD,m);
print_2D(twoD,m,n);
return 0;
}
if 2d is array is declared like this
int arr2D[10][20];
then function declaration must be,
void print_2D(int *arr[20],int m,int n)
or
void print_2D(int arr[][20],int m,int n)

Passing an array to a sort function in C language

#include<stdio.h>
#include<conio.h>
float smallest(int arr[],int k,int n);
void sort(int arr[],int n);
void main()
{
int arr[20],i,n,j,k;
clrscr();
printf("\nEnter the number of elements in the array: ");
scanf("%d",&n);
printf("\nEnter the elements of the array");
for(i=0 ; i < n ; i++)
{
printf("\n arr[%d] = ",i);
scanf("%d",&arr[i]);
}
sort(arr,n);
printf("\nThe sorted array is: \n");
for(i=0 ; i < n ; i++)
printf("%d\t",arr[i]);
getch();
}
int smallest(int arr[],int k,int n)//smallest function
{
int pos=k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void sort(int arr[],int n)//sorting function
{
int k,pos,temp;
for(k=0 ; k < n ; k++)
{
pos=smallest(arr,k,n);
temp=arr[k];
arr[k]=arr[pos];
arr[pos]=temp;
}
}
In the above program the sort function is being called from main but the return type of sort is void and it still returns the sorted array. As after sorting the array the function should return the sorted array back to the calling function to print the sorted array but the program runs perfectly. How is that happening?
When you declare
int arr[20];
you can say "arr is an array of 20 integers". But arr is a pointer to an integer as well, pointing to the first integer in a row of 20. So de-referencing *arr is an integer, the same as arr[0] in fact.
This means when you pass arr to a function you only pass a pointer to that function. The function in this case works on the (copied) pointer. But this very pointer points exactly to the same memory as your original arr declared in main(). And that's the reason why manipulating arr in sort() is in fact manipulating arr in main().
When passing an array as a parameter, this
int smallest(int arr[],int k,int n)
means exactly the same as
int smallest(int *arr,int k,int n)
For example
#include<iostream>
void printArray(int data[])
{
for(int i = 0, length = sizeof(data); i < length; ++i)
{
std::cout << data[i] << ' ';
}
std::cout << std::endl;
}
int main()
{
int data[] = { 5, 7, 8, 9, 1, 2 };
printArray(data);
return 0;
}
You will see that only the first 4 elements of the array are printed. The sizeof(data) returns a value of 4! That happens to be the size of the pointer used to pass the array to printArray().
First the array does not get copied. The pointer to the first element of the array is copied
First, there is no connection between any function argument what is, or is not passed using a return statement with an expression according to the function's return type.
While it is true that all parameter passing in C is by value - copy the value to a "local parameter variable" - nothing is assumed about what is to happen at the memory location a pointer is referencing. So, a function can make any changes in the calling environment, even without returning a value.
As to parameters declared as being aType name[]. this is merely syntactic sugar for const aType* name.

Resources