1

This is a problem for my homework assignment but I am stuck trying to print out the array. The program will prompt the user for the "number of rows" and the "number of columns" but will terminate immediately without printing anything and I am not sure why this is happening.

Also my sorting function doesn't work. The code gives me errors about pointers but am not too familiar with them at this point. If there is a way to do without pointers, I guess that would be better. But if the best method is to use pointers, please include that. The help would be much appreictaed

warning: assignment makes integer from pointer without a cast [-Wint-conversion] temp = A[i];

error: assignment to expression with array type A[i] = A[j];

error: assignment to expression with array type A[j] = temp;

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N1 100

#define M1 100

void fillMatrix(int A[][M1], int N, int M);
int sortMatrix(int A[][M1],int rowsize, int colsize);
void displayArray(int A[][M1], int N, int M);

int main(void)
{
    int array[N1][M1] = {0};

    fillMatrix(array, N1, M1);

    displayArray(array, N1, M1);

    //sortMatrix(array, N1, M1);

    return  0;
}

void fillMatrix(int A[][M1], int N, int M)
{
    int rows = 0, columns = 0;
//ASK FOR ROWS
    printf("Enter a number of rows: ");
    scanf("%i", &rows);

    if(rows < 0 && rows >= 100)
    {
        printf("Invalid Input.\n");
        printf("Enter a number of rows: ");
        scanf("%i", &rows);
    }
//ASK FOR COLUMNS
    printf("Enter a number of columns: ");
    scanf("%i", &columns);

    if(columns < 0 && columns >= 100)
    {
        printf("Invalid Input.\n");
        printf("Enter a number of columns: ");
        scanf("%i", &columns);
    }
//FILLS ARRAY W/ RANDOM INT VALUES BETWEEN 0 AND 100
    srand(time(NULL));

    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
        {
            A[i][j] = 0 + rand() % 100;
        }
    }
}

/*int sortMatrix(int A[][M1],int rowsize, int colsize)
{
    int temp = 0;
    for(int i = 0; i < rowsize; i++)
    {
        for (int j = 0 ; j < colsize; j++)
        {
            if(A[i] > A[j])
            {
                temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            }
        }
    }
    return 0;
}*/

void displayArray(int A[][M1], int N, int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            printf("%i ", A[i][j]);
        }
    }
}
Benjamin John
  • 69
  • 1
  • 8
  • 3
    `A[i]` and `A[j]` are _rows_. You cannot assign whole rows, only elements, e.g. `A[i][j]`. – Paul Ogilvie Jul 12 '18 at 16:34
  • 2
    `if(rows < 0 && rows >= 100)` both can never be true. Use `if(rows < 0 || rows >= 100)` and use `while` so it repeats until a correct number has been entered. – Paul Ogilvie Jul 12 '18 at 16:37
  • 2
    Why pass `int N, int M` as parameters to `fillMatrix` if you don't use them? `main` needs the actual values entered, otherwise sort and print can't work. – Paul Ogilvie Jul 12 '18 at 16:39
  • 1
    You have symbolic constants `M1` and `N1` for the maximum array dimensions. Use those instead of the constant `100`. For examle: `if (n<1 || n>N`) ....` --and-- `printf("Rows must be from 1 to %d\n", N1);` – Mike Housky Jul 12 '18 at 16:47
  • Also, you never did say what the order is for sorting your 2D array. Is `array[0][0]` supposed to receive the (a) smallest entriy in row 0; (b) smallest entry in column 0; or (c) the smallest entry in the whole array? Your code looks like you might be meaning to (d) swap whole rows without reordering the elements in that row; All of those options have different code to implement them. – Mike Housky Jul 12 '18 at 18:12

2 Answers2

2

Yeah, well. First of all sortMatrix(int A[][M1].... In that case, you are passing a pointer to the array row. In C++ there is no other way to pass the array to function, only via pointers. Look over there.

Secondly, when you do something like this A[i] > A[j], you are comparing pointers of rows (In general, comparing pointers is UB, by the way. But, in your case, that is just comparing rows addresses, which is still, not what you should do when you want to sort array). I propose this A[i][M1] > A[j][M1]. That way, you will compare elements.

Last, but not least.

but will terminate immediately without printing anything

Are you mean that console window is closing immediately? In that case, you may need to add cin.get(); to your code, after printing array, or system("pause");, in case you are using clear C, or something like this, if not.

UPD.

  1. If you are using clean C, then instead cin.get(); you should use getchar();.
  2. And system("pause"); truly only Windows thing.

p.s. Also, read other notes from Paul Ogilvie and Mike Housky. They are writing good things.

p.p.s. Pardon, if there is any mistake. English, not my first language, so feel free to edit the answer.

If you have any questions, please do not hesitate to contact me. I will try to answer.

Sviatoslav V.
  • 671
  • 6
  • 18
  • 2
    Comparing pointers into the same array is fully defined behavior. See 6.5.8 (item 5) in the ISO C11 standard. – Mike Housky Jul 12 '18 at 18:01
  • 3
    Also, this is C so `cin.get()` should be `getchar()`; and you should mention that `system("pause");` is WIndows-specific. (Code::Blocks users don't need it, and VS users can avoid it by creating a Win32 Console project, and then using Ctrl+F5 to "Run without debugging.") – Mike Housky Jul 12 '18 at 18:06
  • @Mike Yes, about the same array I mentioned it. Yeah, true about cin. Will edit my post when be at home. Thank you. Also, run without debugging not always work. – Sviatoslav V. Jul 12 '18 at 18:17
  • 1
    It does if the project is specifically a console project; and that even catches a call to `exit()` that bypasses the `system()` call in `main()`. (Yes, `atexit()` should handle that. At some point, firing up Command Prompt and running a command in a command window starts to make sense. :^) – Mike Housky Jul 12 '18 at 20:43
1

The function fillMatrix retrieves two important values from the user, rows and columns, which are needed throughout the program, but these values are lost when the function exits. You then proceed to use fixed values N1 and M1

You should change the function to void fillMatrix(int A[][M1], int *set_rows, int *set_columns) and pass rows and columns by reference so that their values are saved.

if(rows < 0 && rows >= 100)
{
    printf("Invalid Input.\n");
    printf("Enter a number of rows: ");
    scanf("%i", &rows);
}

The valid range for rows should be from 1 to M1. You should also be prepared in case the user enters the wrong value a second time.

There is no standard method to sort the values in a matrix. Do you want to sort each row? You can use qsort to sort a 1-D array.

#define TOTAL_ROWS 100
#define TOTAL_COLUMNS 100
void fillMatrix(int A[][TOTAL_COLUMNS], int *set_rows, int *set_columns)
{
    int rows = 0, columns = 0;

    //ASK FOR ROWS
    while(1)
    {
        printf("Enter a number of rows: ");
        scanf("%i", &rows);
        if(rows > 0 && rows < TOTAL_ROWS)
            break;
        printf("Invalid Input.\n");
    }

    //ASK FOR COLUMNS
    while(1)
    {
        printf("Enter a number of columns: ");
        scanf("%i", &columns);
        if(columns > 0 && columns < TOTAL_COLUMNS)
            break;
        printf("Invalid Input.\n");
    }

    for(int i = 0; i < rows; i++)
        for(int j = 0; j < columns; j++)
            A[i][j] = rand() % 100;

    *set_rows = rows;
    *set_columns = columns;
}

int compare(const void *a, const void *b)
{
    return (*(int*)a - *(int*)b);
}

void sortMatrix(int A[][TOTAL_COLUMNS], int rowsize, int colsize)
{
    for(int r = 0; r < rowsize; r++)
        qsort(A[r], colsize, sizeof(int), compare);
}

void displayArray(int A[][TOTAL_COLUMNS], int rows, int columns)
{
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
            printf("%3i ", A[i][j]);
        printf("\n");
    }
}

int main(void)
{
    srand((unsigned int)time(NULL));
    int array[TOTAL_ROWS][TOTAL_COLUMNS] = { 0 };
    int rows, columns;
    fillMatrix(array, &rows, &columns);
    sortMatrix(array, rows, columns);
    displayArray(array, rows, columns);
    return  0;
}

If you are to use your own sort, or bubble sort specifically, write a simple bubble sort function for a 1-D array, then sort the matrix 1 row at a time:

void bubble_sort(int *arr, int count)
{
    for(int i = 0; i < count - 1; i++)
    {
        for(int j = 0; j < count - i - 1; j++)
        {
            if(arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void sortMatrix(int A[][TOTAL_COLUMNS], int rowsize, int colsize)
{
    for(int r = 0; r < rowsize; r++)
        bubble_sort(A[r], colsize, sizeof(int), compare);
}

Lastly, if rows and columns are not known ahead of time, declaring int array[100][100] is not best way. In gcc compiler you can use variable array. In Visual Studio you have to use malloc in order to dynamically allocate the array based on what the user chooses for rows and columns.

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77