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

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)

Related

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);
}

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.

Accessing an array present in main in a function

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;
}

removing duplicate values from an array in C

I am trying to create a program in C that removes duplicate values in an integer array. My strategy is to first sort the array via a selectionsort function, and then call a function removedup that removes any consecutive, duplicate values in the array.
My code:
#include <stdio.h>
#include "simpio.h"
#define n 10
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
int removedup(int a[]);
void printArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
printf("The original, sorted array is\n");
printArray(a);
printf("The array with removed duplicates \n");
printArray(removedup(a));
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
int removedup(int a[])
{
int i, count, OutArray[count], j;
count=0;
for(i=0;i<n-1;i++)
{
if(a[i]==a[i+1])
{
a[i+1]=a[i+2];
count++;
}
}
count++;
for(j=0;j<count;j++)
{
OutArray[i]=a[i];
}
return OutArray;
}
I have two questions:
1) How do I fix the error the compiler in giving me in the main body when calling removedup inside the printarray function, saying "invalid conversion from int to int*"? (line 22)
2) How do I accurately define the size of OutArray[] in the removedup function? Currently I have it defined as the size variable, but the value of this variable isn't accurately defined until after the declaration of OutArray.
Notice your prototypes ...
int removedup(int a[]);
void printArray(int a[]);
And also notice you're calling printArray() with the result of removedup().
printArray(removedup(a));
The result of removedup() is an int; printarray() requires a int[].
int and int[] are not compatible.
I suggest you remove duplicates and print array in two distinct statements.
You should be able to fix the compiling problems after reading comp.lang-c FAQ on arrays and pointers.
After you get your array sorted, you can use the following function to remove the duplicates:
int dedup(int arr[], int size) {
int curr = 0, next = 0;
while (next < size) {
while (next < size && arr[next] == arr[curr])
next++;
if (next < size)
arr[++curr] = arr[next++];
}
return size ? curr+1 : 0;
}
It takes two arguments, the array and its size. The duplicates are removed in-place, which means that the array is modified, without allocating a new array to store the unique elements.
Remember that the dedup function expects the elements to be sorted! I've noticed you are using your own implementation of selection sort, which makes me think this is homework. In that case, I feel a little reluctant on giving you a complete solution, although understanding it should be a good exercise anyway.
EDIT: I should've explained the last line of code.
return size ? curr+1 : 0; is equivalent to:
if (size)
return curr+1;
else
return 0;
Just a shorter way of saying the same thing.

passing statically allocated 2D arrays as function arguments in C

Consider this code:
#include <stdio.h>
#define N 5
void printMatrix(int (*matrix)[N],int n)
{
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d",matrix[i][j]);
printf("\n");
}
}
int main()
{
int R[N][N]={{1,2,3},{4,5,6},{7,8,9}};
printMatrix(R,3);
}
This works fine as expected.
Now, I thought to write the functions handling 2D-matrices in a separate source file and link them wherever required.
But then I ran into a problem as in the function printMatrix, the size of array of int to which matrix points (i.e N) is required at compile-time. So, my functions would not work in other cases when the size is different.
So,How can I handle this?
Dynamic Arrays are a solution but i want to know if it can be done with static arrays.
You can't use the built-in 2D array type if both sizes are not known at compile time. A built-in 2D array must have at least one of the two sizes known at compile time.
If both sizes are run-time values, then you have no other choice but to use a "manual" implementation of 2D array, like an array of pointers to arrays, for example. In that case the function declaration might look as follows (two alternative equivalent forms)
void printMatrix(int *const *matrix, int n, int m);
void printMatrix(int *const matrix[], int n, int m);
To access to the array elements you can still use the "traditional" syntax
matrix[i][j]
The array itself would be created as follows (a simple example)
int row0[] = { 1, 2, 3 };
int row1[] = { 4, 5, 6 };
int *matrix[2];
matrix[0] = row0;
matrix[1] = row1;
printMatrix(matrix, 2, 3);
But if you already have a matrix implemented as a built-in 2d array
int matrix[2][3] = { ... };
then just to be able to pass it to the above function you can "convert" it into the above form by using an additional temporary "row pointer" array
int *rows[2];
rows[0] = matrix[0];
rows[1] = matrix[1];
printMatrix(rows, 2, 3);
Write yourself a macro:
#define MAT(i,j) matrix[i*n + j];
and declare "matrix" as a simple pointer to an "int".
Calculate the array index yourself. This will handle an arbitrary two dimensional array, for example:
void printMatrix(int *matrix,int n, int m)
{
int i,j;
for(i=0;i<n;i++){
for(j=0;j<m;j++)
printf("%d",matrix[m * i + j]);
printf("\n");
}
}
Don't try to pass it as a 2-D array; pass a pointer to the first element, then compute offsets manually:
void printMatrix(int *a, size_t m, size_t n)
{
size_t i,j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("a[%lu][%lu] = %d\n",
(unsigned long) i,
(unsigned long) j,
a[i*n+j]); // treat a as 1-d array, compute offset manually
}
}
}
int main(void)
{
int arr[5][4];
...
printMatrix(&arr[0][0], 5, 4);
...
}
Granted, this will only work for contiguously allocated arrays.
Although the syntax is not exactly the same, but this also happens to work a bit:
#include <stdio.h>
#define N 5
void printMatrix(int* row,int n,int sz)
{
int i,j;
int *currRow;
for(i=0;i<n;i++){
currRow = row+i*sz;
for(j=0;j<n;j++)
printf("%d",currRow[j]);
printf("\n");
}
}
int main()
{
int R[N][N]={{1,2,3},{4,5,6},{7,8,9}};
printMatrix(R[0],3,sizeof(R[0])/sizeof(int));
}

Resources