Home > OS >  Moving rows by one in a 2d array in c?
Moving rows by one in a 2d array in c?

Time:12-26

Disclamer:Im a beginner. So I had for my homework to write a program that moves rows, for example, row 0 to row 1,row1 to row 2, row 2 to row 0. A 3x3 matrix is in question. I wrote the code but it seems to not work, it shows numbers like -858993460. Here is my attempt(part of my code):

#include<stdio.h>
int main(){
    int a[10][10], n, m, i, j, k, l,transpose[10][10];
    printf("Enter number of rows: ");
    scanf_s("%d", &n);
    printf("Enter number of columns: ");
    scanf_s("%d", &m);
    printf("Enter elements of the matrix: ");
    for ( i = 0; i < n; i  )
    {
        for ( j = 0; j < m; j  )
        {
            scanf_s("%d", &a[i][j]);
        }

    }
    for (i = 0; i < n; i  )
    {
        for (j = 0; j < m; j  )
        {
            printf("%d\t", a[i][j]);
        }
        printf("\n");
    } 
for (i = 0; i < n; i  )
    {
        for (j = 0; j < m; j  )
        {
            a[i][j] = a[i   1][j];
                a[n - 1][n - 1] = a[0][0];
        }
        
    }
    printf("\n The new matrix is: \n");
    for (i = 0; i < n; i  )
    {
        for (j = 0; j < m; j  )
        {
            printf("%d\t", a[i ][j]);
        }
        printf("\n");
    }  ``

CodePudding user response:

One way to solve this would be to have an array of pointers to int.

So you create an array of 3 pointers to int arrays of values

then just change what the pointers point to.

int * a[3]; // declares 3 pointers to arrays of int

now for each point allocate memory to hold the 3 int values

a[0] = malloc(sizeof(int)*3);
...

 ------       -- -- -- 
| a[0] | --> |  |  |  |
 ------       -- -- --   
| a[1] | --> |  |  |  |
 ------       -- -- -- 
| a[2] | --> |  |  |  |
 ------       -- -- -- 

now you have three pointers to three allocated memory areas that can hold 3 int values.

to swap say a[1] with a[2] just do

int* tmp = a[1];
a[1] = a[2];
a[2] = tmp;

and Bob is your uncle

CodePudding user response:

Let us assume n = 3, m = 3. When i = 2, j = 0; this line a[i][j] = a[i 1][j]; becomes a[2][0] = a[3][0].
In this case, a[3][0] is not initialized. ith index 0, 1, 2 is initialized not 3. Therefore, you are getting unexpected values.

Here is some modification to your last two nested loops to generate the expected output.

for (i = 0; i < n; i  )
{
    for (j = 0; j < m; j  )
    {
        transpose[i][j] = a[(i   1)%n][j];
        //a[n - 1][n - 1] = a[0][0];
    }
    
}
printf("\n The new matrix is: \n");
for (i = 0; i < n; i  )
{
    for (j = 0; j < m; j  )
    {
        printf("%d\t", transpose[i][j]);
    }
    printf("\n");
} 
  • Related