-3

i need code for modifying an 2d array by passing it into a function so that what ever i write in function original array should get modified

#include<stdio.h>
void display(int *arr){
    for(int i = 0;i < 4;i++){
        printf(" %d " , arr[i]);
    } 
}
void modify(int *arr){
    arr[0] = arr[1]; 
}
int main() {
    int a[4] = {0,1,2,3};
    display(a);
    modify(a);
    display(a);
}
}

output is 0123 1123 for an 1d array how do you code for 2d array ----------

#include<stdio.h>
void pass(int *arr,int n){
    arr[0][0]=arr[0][1];   
}
int main() {
   int n,i,j;
    scanf("%d",&n);
    int a[n][n];
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            scanf("%d",&a[i][j]);
        }
    }
    pass(a,n);
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%d",a[i][j]);
        }
    }
 }

im getting an error for 2d array

virus
  • 13
  • 3
  • 2
    You have declared 1d array but using it as 2d array. – kiran Biradar Jul 14 '19 at 14:06
  • 1
    Possible duplicate of [Passing a 2D array to a C++ function](https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function) – Sam Varshavchik Jul 14 '19 at 14:08
  • https://stackoverflow.com/users/4431643/kiran-biradar that was done in a mistake now do check again please – virus Oct 03 '19 at 04:30
  • https://stackoverflow.com/users/3943312/sam-varshavchik i requested for referencing the array you quoted for pass int array – virus Oct 03 '19 at 04:31

2 Answers2

1

To have a two dimension array use a[n][n].
To pass that variable length array to a function, pass the size, int n, and then a pointer to the array, int (*arr)[n].

#include<stdio.h>

void pass ( int n, int (*arr)[n]){
    arr[0][0] = arr[0][1];
}
int main ( void) {
    int n,i,j;

    printf ( "enter array size\n");
    scanf ( "%d", &n);
    int a[n][n];

    for ( i = 0; i < n; i++) {
        for ( j = 0; j < n; j++) {
            printf ( "enter array[%d][%d] value\n", i, j);
            scanf ( "%d", &a[i][j]);
        }
    }

    pass ( n, a);

    for ( i = 0; i < n; i++) {
        for ( j = 0; j < n; j++) {
            printf ( "%d\t", a[i][j]);
        }
        printf ( "\n");
    }
    return 0;
}
user3121023
  • 6,995
  • 5
  • 14
  • 13
0
#include<stdio.h>
void pass(int arr[][100], int n) {
    arr[0][0] = arr[0][1];
}
int main() {
    int n, i, j;
    scanf_s("%d", &n);
    int a[100][100];
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            scanf_s("%d", &a[i][j]);
        }
    }
    pass(a, n);
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%d", a[i][j]);
        }
    }
}
nivpeled
  • 1,605
  • 2
  • 16