2D array passing to a function - c

I've been reading this question but I'm not able to get the resulting code to solve the problem.
How should I change this in order to make it work?
void print2(int ** array,int n, int m);
main()
{
int array[][4]={{1,2,3,4},{5,6,7,8}};
int array2[][2]={{1,2},{3,4},{5,6},{7,8}};
print2(array,2,4);
}
void print2(int ** array,int n,int m)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i][j]);
printf("\n");
}
}

You are passing in a pointer to an array, but your function is expecting a pointer to a pointer. In C, the array name decays to a value that is the pointer to the first array element. In this case, the first array element is an array, so the function argument decays to a pointer to an array.
Here is one way you can fix this. Change the function to take a void * so that the dimension does not interfere with the argument. Then the dimension argument is used in the function body to create the proper pointer type for the 2D array.
void print2(void *p,int n,int m)
{
int i,j;
int (*array)[m] = p;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i][j]);
printf("\n");
}
}
If you are willing to change the order of the arguments, then you can use the proper type for the array argument:
void print2(int n, int m, int array[n][m])
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i][j]);
printf("\n");
}
}
Since Jack asked about C89, here's a way to handle it. Since a 2D array is organized the same as a long 1D array in memory, you can just walk the passed in pointer as such. Again, we accept the input parameter as a void * to avoid dealing with the decayed type. Then, we treat the pointer as a long 1D array, but we walk it according to the proper dimensions:
void print2(void *p, int n, int m)
{
int i,j;
int *array = p;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i*m+j]);
printf("\n");
}
}

In your question you are passing arguments as pointer to an array.
Do as given below :
void print2(int (*array)[4],int n,int m)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d ",array[i][j]);
printf("\n");
}
}

Related

Two array merge into a third array in c

For some Reason the Program Crashes at the Loop used to merge the two arrays in main.
though maybe this question is a foolish in one(idk it didn't allow me to post as my program is mostly code so now i am blabbering).
(Well it still doesn't so here's a Picture of a Cat
CAT )
//To make two arrays of user Defined Size and merge them in a third array
#include<stdio.h>
#include<stdlib.h>
void array(int**,int);
void ini(int**,int);
void display(int **,int);
int main()
{
int *a1,*a2,*a3,s1,s2,i,j;
printf("Enter Size of Array 1\n");
scanf("%d",&s1);
printf("Enter Size of Array 2\n");
scanf("%d",&s2);
ini(&a1,s1);
ini(&a2,s2);
ini(&a3,s1+s2);
printf("Enter Elements of Array 1\n");
array(&a1,s1);
printf("Array 1:\n");
display(&a1,s1);
printf("Enter Elements of Array 2\n");
array(&a2,s2);
printf("Array 2:\n");
display(&a2,s2);
for(i=0;i<s1;i++)
{
a3[i]=a1[i];
}
for(i=0,j=s1;i<s2&&j<s1+s2;i++,j++)
{
a3[j]=a2[i];
}
printf("Merged Array:\n");
display(&a3,s1+s2);
return 0;
}
void ini(int **a,int s)
{
*a=(int*)calloc(s,sizeof(int));
}
void array(int **a,int s)
{
int i;
for(i=0;i<s;i++)
{
printf("Enter Element at position %d\n",i+1);
scanf("%d",&a[i]);
}
}
void display(int **a,int s)
{
int i;
for(i=0;i<s;i++)
{
if(i==s-1)
printf("%d\n",a[i]);
else
printf("%d\t",a[i]);
}
}
a1, a2, and a3 is a pointer of an integer type variable, which stores the starting address of your buffer.
a1[index] is the value in the address of a1 with 'index' as the offset.
Since you were passing &a to your array() and display() function, you were passing the address of your variable into the function instead of passing the address of your buffer.
You could change your array() and display() to:
void array(int *a,int s)
{
int i;
for(i=0;i<s;i++)
{
printf("Enter Element at position %d\n",i+1);
scanf("%d", &(a[i]));
}
}
void display(int *a,int s)
{
int i;
for(i=0;i<s;i++)
{
if(i==s-1)
printf("%d\n", a[i]);
else
printf("%d\t", a[i]);
}
}
and call it like this:
array(a1,s1);
display(a1,s1);

Finding largest element in a array using call by reference ( Functions & Pointers )

I want to find the largest element in an array using call by reference method that is functions and pointers. I am getting an error at function call. Here is my try:
#include <stdio.h>
void bigg(int *a[10],int *N);
int main()
{
int a[10],i,N,p;
printf("Enter the total number of elements in the array:\n");
scanf("%d",&N);
printf("Enter the elements in the array one by one:\n");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
bigg(&a,&N);
}
void bigg(int *a[10],int *N)
{
int i,max;
max = *a[0];
for(i=0;i<*N;i++)
{
if( *a[i] > max)
{
max = *a[i];
}
}
printf("The biggest element in the given array is: %d",max);
}
Your basics of pointer is not clear.
For this question it works.
#include <stdio.h>
void bigg(int a[],int *N);
int main()
{
int a[10],i,N,p;
printf("Enter the total number of elements in the array:\n");
scanf("%d",&N);
printf("Enter the elements in the array one by one:\n");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
bigg(a,&N);
}
void bigg(int a[],int *N)
{
int i,max;
max = a[0];
for(i=0;i<*N;i++)
{
if( a[i] > max)
{
max = a[i];
}
}
printf("The biggest element in the given array is: %d",max);
}
What you're passing doesn't match the expected argument.
The function bigg is expecting for it's first argument an int *[10] which is an array of pointers. You're passing it &a which is a pointer to an array and has type int (*)[10].
You actually don't want either of these. An array name is, in most contexts, converted to a pointer to its first element. So if you pass that you'll have access to the elements. So change your function definition to accept an int * for the first argument (and an int for the second since you're not changing N):
void bigg(int *a, int N)
{
int i,max;
max = a[0];
for(i=0;i<N;i++)
{
if( a[i] > max)
{
max = a[i];
}
}
printf("The biggest element in the given array is: %d",max);
}
And call it like this:
bigg(a,N);

using #define in functions

How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.

Passing array to function using pointer

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Passing an array as an argument to a function pointer in C

I'm currently studying pointers to functions and have been practicing on sort array functions.
The point is I input a sequence of numbers into the function and the program will re arrange it in ascending order. It worked just fine when I do a call by value function (I think that's how you call it). However when I try to assign a pointer to function and try to use that pointer instead of the function itself, it returns a bunch of errors. I'm sure the problem is due to the fact that I'm passing an array as an argument to the function POINTER. Here is my code:
#include<stdio.h>
#define SIZE 10
void sort(int a[], int size);
void swap(int *elt1, int *elt2);
main()
{
int i; int array[SIZE]= {1,9,3,2,4,100,43,23,32,12};
void (*fptr)(int array, int SIZE);
fptr = &sort;
(*fptr)(array,SIZE);
/*sort(array, SIZE);*/
for(i=0;i<SIZE;i++)
{
printf("%d\n", array[i]);
}
return 0;
}
void sort(int a[], int size)
{
int pass, j;
for(pass = 0; pass<size;pass++)
{
for(j=0;j<size;j++)
{
if(a[j]>a[j+1])
{
swap(&a[j], &a[j+1]);
}
}
}
}
void swap(int *elt1, int *elt2)
{
int hold;
hold = *elt1;
*elt1 = *elt2;
*elt2 = hold;
}
The first argument of the function is a pointer to int (that is, int *), and not int.
void (*fptr)(int array, int SIZE);
should be
void (*fptr)(int *array, int SIZE);

Resources