I have a 2D array in which many elements are zero. For example:
int array[10][10];
memset(array, 0, 100 * sizeof(int));
array[0][0] = 3;
array[2][8] = 5;
array[4][0] = 4;
How could I print the non-zero (only positive) elements in descending (or ascending) order. I was thinking about something like this:
int xpos, ypos;
while (getMaximumInArray(array, &xpos, &ypos))
{
printf("x=%i y=%i val=%i\n", xpos, ypos, array[xpos][ypos]);
array[xpos][ypos] = 0; // set to 0 to make sure we find the next biggest value.
}
However this makes me loop through the array many times (as much as there are non-zero elements). Would there be a better (ie less operations) way to do this?
EDIT : I forgot to specify that I would like to use the positions in my output; so I need not only the sorted values; but also their indices...
A simple way to make this more efficient is to simply sort the values. Sorting - or copying while sorting - has runtime complexity of O(n log n) which is an improvement over your O(n*n). An easy and efficient way to do that is to copy the non-zero values to a std::multiset and then iterate through it.
Update regarding your edit:
No problem. Simply store an object that contains the value and the indices in the set and supply a comparison functor that uses only the value.
You could create new array and then sort it.
For example:
int array[10][10];
array[0][0] = 3;
array[2][8] = 5;
array[4][0] = 4;
int positive[100];
int k = 0;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
if(array[i][j] > 0){
positive[k++] = array[i][j];
}
}
}
sort(positive, positive + k);
for(int i = 0; i < k; i++){
printf("%d", positive[i]);
}
There are multiple approaches to this. Denis Gavrus proposed using an array, which is fine, but you can use a vector if you want to be more memory efficient:
Also, if you need to keep your values and their position, you'll need to store them in a struct/class (the ELEMENT struct), which will need a separate comparison class/function.
Here is the container and the comparison function:
struct ELEMENT{ ///Containing the value and the coordinates
int val, i, j;
};
bool cmp(ELEMENT a, ELEMENT b){
return a.val<b.val;
}
And here is the code that processes your data:
const int L=10; ///In case you want to modify the matrix dimensions
int array[L][L]; ///A really bad name for anything
vector<ELEMENT> v; ///The vector containing the sorted values
for(int i=0; i<L; i++) ///Initialize the matrix with 0
for(int j=0; j<L; j++)
array[i][j]=0;
array[0][0] = 3; ///Your values...
array[2][8] = 5;
array[4][0] = 4;
for(int i=0; i<L; i++)
for(int j=0; j<L; j++)
if(array[i][j]!=0)
v.push_back({array[i][j], i, j}); ///Insert into v the non-zero values and the coordinates
sort(v.begin(), v.end(), cmp);
for(ELEMENT i:v)///Your output
printf("%d at position (%d, %d)\n",i.val, i.i, i.j);
Also, you could use a priority queue:
The comparison class for the priority queue:
class cmp{ ///Containing the functor for the priority queue
public:
bool operator()(ELEMENT a, ELEMENT b){
return a.val<b.val;
}
};
The code that does stuff:
const int L=10; ///In case you want to modify the matrix dimensions
int array[L][L]; ///A really bad name for anything
priority_queue<ELEMENT, vector<ELEMENT>, cmp> v; ///The priority queue containing the sorted values
for(int i=0; i<L; i++) ///Initialize the matrix with 0
for(int j=0; j<L; j++)
array[i][j]=0;
array[0][0] = 3; ///Your values...
array[2][8] = 5;
array[4][0] = 4;
for(int i=0; i<L; i++)
for(int j=0; j<L; j++)
if(array[i][j]!=0)
v.push({array[i][j], i, j}); ///Insert into v the non-zero values
for(; !v.empty(); v.pop())
printf("%d at position (%d, %d)\n",v.top().val, v.top().i, v.top().j);
Related
I want to construct a function that takes a matrix as input and then calculates the means of all rows (or columns). I tried to do it like this, but it gives me a bunch of errors.
#include <stdio.h>
#include <stdlib.h>
int sum_rows[1000], sum_columns[1000], mean_row[1000], mean_column[1000], N, A[100][100], i, j;
void values(int A[N][N]) {
for (i=0; i<N; ++i) {
for (j=0; j<N; ++j) {
A[i][j] = (rand()%61+20);
}
}
}
void mean_r (int A[N][N]) {
for (i=0; i<N; ++i) {
sum_row[i] = 0;
for (j=0; j<N; ++j) {
sum_row[i] += A[i][j];
}
mean_row[i] = sum_row[i]/N;
}
}
void mean_c (int A[N][N]) {
for (j=0; j<N; ++j) {
sum_column[j] = 0;
for (i=0; i<N; ++i) {
sum_column[j] += A[i][j];
}
mean_column[j] = sum_column[j]/N;
}
}
int main()
{
int N;
printf("Enter size of matrix: ");
scanf("%d", &N);
int A[N][N];
values(A[N][N]);
mean_r(A[N][N]);
mean_c(A[N][N]);
for (i=0; i<N; ++i) {
for (j=0; j<N; ++j) {
printf("A[%d][%d] = %d\n", i, j, A[i][j]);
}
}
for (i=0; i<N; ++i) {
printf("Mean row #%d = %.2f\n", i, mean_row[i]);
}
for (j=0; j<N; ++j) {
printf("Promedio Columna #%d = %.2f\n", j, mean_column[j]);
}
return 0;
}
Can you explain to me how to pass a matrix into a function? I have to do these operations with a function defined beforehand, and just call it inside the main function.
It seems that your matrix is dynamic(the number of of rows and columns are not fixed). In C language, you are not allowed to declare the array of array with the dynamic rows and columns because the compiler does not know how to allocate the how much memory for you. You will have to allocate the memory at run-time. In my example, the matrix is stored in the memory as first row, the second row and so on. In math, the access to the element of the matrix is by row index and column index. "row index and column index" is translated to the memory address of the element using the starting address of the memory allocated + row number * column number + the column index based on how the matrix is stored in my example. Note: both row number and column number start with zero. The first element is denoted by p where p+0*columncount+0) is p. The next element is denoted by p+0*columncount+1. Following this, the element of the second row and second column(2,2) is denoted by p+1*column count+1. The following example uses single pointer to represent the dynamic matrix(Other technique does exist, eg. the pointer array)
In my example, 3(three rows) by 4(four columns) matrix is created and initialized. The ProcessMatrix function display the sum of each row.
If possible, I recommend you use C++ that allows you to allocate the memory with the size specified by the value of one integer, which makes things more easier. If you have access to other math libraries(many available), you should use them instead of trying to reinvent wheel.
// c_matrix.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
int GetElementValue(int* m, int rowIndex, int colIndex, int columnCount)
{
return *(m + (rowIndex * columnCount + colIndex));
}
void ProcessMatric(int* myMatrix, int rowcount, int colcount)
{
// calculate the sum of each row
int sum = 0;
for (int i = 0; i < rowcount; i++)
{
sum = 0;
for (int j = 0; j < colcount; j++)
{
sum = sum + GetElementValue(myMatrix, i, j, colcount);
}
printf("Sum of row %d=%d\r\n", i+1, sum);
}
}
int main()
{
int row = 3;
int col = 4;
int* matrix;
//create the memory for the matrix 3 by 4.
matrix = malloc(sizeof(int) * row * col);
// in momery the matrix is stored as (row1,col1), (row1, col2), (row1,col3)...(row4,col1),(row4,col2),(row4, col3)
// initialize the matrix as 0,1,2,3...11
for (int i = 0; i < row * col; ++i)
{
*(matrix + i) = i;
}
ProcessMatric(matrix, row, col);
free(matrix);
return 0;
}
In your main function you declare an NxN matrix A
int A[N][N];
As Yan pointed out, you are unable to declare the array in such a way because the compiler doesn't know the value of N. The value of N won't be determined until after the program has been compiled and is executing (i.e. during runtime). Beyond that, though, it seems like what you want to do is pass the 2d array. What you need to pass is A itself (e.g. values(A);, however you pass
values(A[N][N]);
mean_r(A[N][N]);
mean_c(A[N][N]);
What you've done is index both dimensions, so, normally what would happen is you would just be passing an int (whatever is in the Nth row and Nth column). However, indices are in the range [0, N-1] so A[N] is out-of-range. They key concept is that arrays (and other data structures) are passed by reference. When you declare A, contiguous space will be allocated to hold N * N * sizeof(int) and the virtual address for the starting location of that space is stored in A. As a result, your functions know what memory addresses to store stuff in so that you can access it with A[i][j] without having to pass a giant slab of memory.
I'm building a program that is saving information on a matrix of Pixels (a struct). A pixel must have its color (another struct) the color is a struct with three integers (red=vermelho, green=verde and blue=azul). But when I set them their value change right after the end of the for.
For example, if I put the value 250 on all the red attributes of pixels it somehow changes if I print them after the for is finished if I print them while the for is running the values are right.
I'm also reading the information of the value of the red, green and blue values of a file, but I printed them and they are right.
Bellow are the functions that I'm using, and I'm having problems in the function clear from it I'm getting "250 0 0" (the right value) for all the pixels inside the for but the values change being sometimes "250 0 0", "0 250 0" and "250 250 0" in the second for inside the clear function.
I've tried printing all the variables, but it seems they somehow magically change after I set them in the first for. I'm not really experienced at C so I'm really lost right now.
typedef struct cor{
int vermelho;
int verde;
int azul;
} Cor;
typedef struct pixel{
Cor cordopixel;
} Pixel;
typedef struct imagem{
Pixel **pintura;
int largura;
int altura;
} Imagem;
void image(FILE *pont_arq, Imagem *desenho){
int i, j, k;
fscanf(pont_arq, "%d %d", &i, &j);
desenho->altura = j; //value equals 400
desenho->largura = i; //value equals 600
printf("Cria imagem %dx%d\n", i, j);
desenho->pintura = calloc(i, sizeof(Pixel*));
for (k = 0; k < i; ++k){
desenho->pintura[k] = calloc(j, sizeof(Pixel));
}
printf("Saiu\n");
}
int* lerIntArquivo(FILE *pont_arq, int inicio, int vezes, int val[]){
if(vezes==inicio-1){
fscanf(pont_arq, "%d", &val[inicio]);
return val;
}else{
fscanf(pont_arq, "%d", &val[inicio]);
lerIntArquivo(pont_arq, inicio+1,vezes, val);
}
}
void clear(FILE *pont_arq, Imagem *desenho){
int val[3], i, j;
lerIntArquivo(pont_arq, 0, 3, val);
printf("Cria imagem");
printf("%d %d %d\n",val[0],val[1], val[2]); //val[0]=250 val[1]=0 val[2]=0
//this for is printing the right values
for (i = 0; i < desenho->altura; ++i){
for (j = 0; j < desenho->largura; ++j){
printf("%d %d\n",i,j);
desenho->pintura[i][j].cordopixel.vermelho = val[0];//setting the values
desenho->pintura[i][j].cordopixel.verde = val[1];//setting the values
desenho->pintura[i][j].cordopixel.azul = val[2];//setting the values
printf("%d ", desenho->pintura[i][j].cordopixel.vermelho);
printf("%d ", desenho->pintura[i][j].cordopixel.verde);
printf("%d\n", desenho->pintura[i][j].cordopixel.azul);
}
}
//this for is not printing the right values
for (i = 0; i < desenho->altura; ++i){
for (j = 0; j < desenho->largura; ++j){
printf("%d ", desenho->pintura[i][j].cordopixel.vermelho);
printf("%d ", desenho->pintura[i][j].cordopixel.verde);
printf("%d\n", desenho->pintura[i][j].cordopixel.azul);
}
}
printf("\n");
}
There were no error messages, just wrong values.
When you allocate memory for your image the value of largura is the first size of the 2D array and the value of altura is its second size
desenho->altura = j;
desenho->largura = i;
...
desenho->pintura = calloc(i, sizeof(Pixel*));
for (k = 0; k < i; ++k){
desenho->pintura[k] = calloc(j, sizeof(Pixel));
}
I.e. you create an array of [largura][altura] size.
But when you latter work with the array you suddenly reverse their roles
for (i = 0; i < desenho->altura; ++i){
for (j = 0; j < desenho->largura; ++j){
...
desenho->pintura[i][j]
I.e. you access it as a [altura][largura] array, which is incorrect.
At some step you managed to swap the values. Most likely, when you allocated the image memory it was supposed to be
desenho->altura = i;
desenho->largura = j;
not the other way around.
I am writing a program where I take 2 one dimensional arrays and generate a matrix in its most simplified form Ax=b.
This part of the function takes in the arrays A and b. A is A[n*n] and b is b[n]. In this section I tried to combine the two arrays so it looks like an actual matrix.
This code works, however, if n were to be greater than 1023 it would cause a segmentation fault when calling the main function. I was wondering if there is a better way in doing this. When I tried to use the GDB debugger, it stoped at the line Y[i][j] = A[k]; so I think this is the problem that requires fixing
int linsolve ( int n, double A[], double b[], double x []) {
double Y[n][n+1]; //Creating multidimensional matrix
int k = 0;
// Turns the two one dimensional array into one multidimensional
for (int i=0; i < n; i++){ //iterating row
for (int j=0; j < n; j++){ // per column
Y[i][j] = A[k]; // adding from array A to Y
k++;
}
Y[i][n] = b[i]; // adding from Array b to Y
}
I assume you are using a Unix/Linux type system. First find out the stack size by typing
ulimit -s
This is the stack size in kilobytes. On my system it is 8Mb. If you have a 1200x1200 matrix, that will require
1200x1201x8 appx 10Mb
This is why the program segvs. You are creating 10Mb array on an 8Mb stack. The question is, does A or b live on the stack too? You may be getting a segv because the item you are passing through was created on the stack and is larger than the allocated stack.
To solve it, create the array on the heap as #shirish has suggested. An alternative to #shirish's technique would be
int linsolve ( int n, double A[], double b[], double x []) {
double **Y = new double *[n];
double *Ybody = new double[n * (n + 1)];
for (int i = 0; i < n; i++) {
Y[i] = &Ybody[i * (n + 1)];
}
// Turns the two one dimensional array into one multidimensional
int k = 0
for (int i=0; i < n; i++){
for (int j=0; j < n; j++){
Y[i][j] = A[k++];
}
Y[i][n] = b[i];
}
// Do something
// Free up Y before returning
delete [] Y;
delete [] Ybody;
}
// Assuming A has n * n elements
int linsolve ( int n, double A[], double b[], double x []) {
double **Y = new double *[n];
for (int i = 0; i < n; i++) {
Y[i] = new double[n + 1];
}
int k = 0;
// Turns the two one dimensional array into one multidimensional
for (int i=0; i < n; i++){ //iterating row
for (int j=0; j < n; j++){ // per column
Y[i][j] = A[k++]; // adding from array A to Y
}
Y[i][n] = b[i]; // adding from Array b to Y
}
// Do something
// Free up Y before returning
for(int i = 0; i < n; i++) {
delete [] Y[i];
}
delete [] Y;
//Return int here
}
Part of my assignment is to sort a 2D array into ascending order, and I cannot figure out how to do it for the life of me.
What I have so far:
int Sort2DArray(int A[][COL], unsigned int rowsize, unsigned int colsize)
{
int i, j, k, temp;
for (i=0; i<rowsize-1; i++){
for (k=0; k<colsize; k++){
for (j=0; j<rowsize-1; j++){
do {
temp = A[k][j];
A[k][j] = A[k][j+1];
A[k][j+1] = temp;
} while (A[k][j]>A[k][j+1]);
}
}
}
}
This will take an array this and return:
3 2 1 1 2 3
5 8 7 ---->>> 5 7 8
4 9 3 3 4 9
However, I need it to return:
1 2 3
4 5 6
7 8 9
So, is there any way you guys can help me? Thanks!
EDIT:
#include <stdio.h>
#include <stdlib.h>
#define COL 20
#define ROW 20
void PopulateArray2DUnique (int [][COL], unsigned int, unsigned int, int, int);
void DisplayArray2D(int [][COL], unsigned int, unsigned int);
int FindLargest(int [][COL], unsigned int, unsigned int);
int FindColSum(int [][COL], unsigned int, unsigned int, unsigned int);
int Sort2DArray(int [][COL], unsigned int, unsigned int);
int main()
{
int A[ROW][COL];
int min=1, max=99;
unsigned int rowsize, colsize, col_to_sum;
printf ("Input your desired row and column size: \n");
scanf ("%u%u", &colsize, &rowsize);
PopulateArray2DUnique(A, rowsize, colsize, min, max);
DisplayArray2D(A, rowsize, colsize);
FindLargest(A, rowsize, colsize);
printf ("Which column would you like to find sum of?\n");
scanf ("%d", &col_to_sum);
FindColSum(A, rowsize, colsize, col_to_sum);
Sort2DArray(A, rowsize, colsize);
DisplayArray2D(A, rowsize, colsize);
return 0;
}
Is it possible?
Yes, it's possible. The most important thing to understand is that your sort routine, and all of the basic sort routines you see in examples, generally sort a 1D array.[1] The same routine can be used to sequentially sort a 2D array as you are attempting to do, but you have to recognize you want to pass your 2D array to the sort function as a pointer-to-type (simple 1D array, e.g. 'int *'), rather than as a pointer-to-array of X elements (your 2D array, e.g. 'int (*)[NCOLS]')
The key to passing the array is to simply pass the address to the first element in your array. Regardless of whether you declared it as a 1D or 2D array (1) that is the address where the values begin in memory; and (2) all array values are sequential. Meaning that you can address every value in a 1D or 2D array by start_address + offset.
Take for example your simple bubble-sort routine:
void bubblesort (int *a, size_t n)
{
size_t i, j;
int temp;
for (i = 0; i < n; i++) {
for (j = 0; j < (n-1); j++) {
if (a[j] > a[j + 1]) {
temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
}
If you had declared a 2D array (e.g. int array[][NCOL];, not pointer-to-pointer-to-type int **array;) that you wished to sequentially sort, you could call your sort routine by simply passing the start address as follows:
bubblesort (*array, nelem);
or
bubblesort (&array[0][0], nelem);
(both are equivalent, with 'nelem' being the total number of elements)
If you attempt to declare your sort function by passing a pointer to array (e.g. bubblesort (int (*array)[NCOL], size_t n); you will run difficulty immediately attempting to loop over the indexes because using the traditional nested loop layout, there is no easy way to compare array[i][j] with array[i+1][0], etc..
The following is a short example putting it all together. Look it over and let me know if you have questions:
#include <stdio.h>
#include <stdlib.h>
#define NCOL 3
void bubblesort (int *a, size_t n);
int main ()
{
int array[][NCOL] = {{3,2,1},
{5,8,7},
{4,9,3}};
int i, j, nrows, nelem;
nrows = sizeof array/sizeof *array;
nelem = sizeof array/sizeof **array;
printf ("\noriginal:\n\n");
for (i = 0; i < nrows; i++) {
for (j = 0; j < NCOL; j++)
printf (" %2d", array[i][j]);
putchar ('\n');
}
bubblesort (*array, nelem);
printf ("\nsorted:\n\n");
for (i = 0; i < nrows; i++) {
for (j = 0; j < NCOL; j++)
printf (" %2d", array[i][j]);
putchar ('\n');
}
return 0;
}
void bubblesort (int *a, size_t n)
{
size_t i, j;
int temp;
for (i = 0; i < n; i++) {
for (j = 0; j < (n-1); j++) {
if (a[j] > a[j + 1]) {
temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
}
Output
$ ./bin/qsort_2d_linear
original:
3 2 1
5 8 7
4 9 3
sorted:
1 2 3
3 4 5
7 8 9
Note: you can do the same thing with qsort rather easily with the standard integer compare function and calling qsort (array, nelem, sizeof **array, icompare);
footnote[1]: all arrays in C are 1D arrays, the 2D array is simply addressed in a way to allow 2D indexing. It is still a sequential block of 'type' values in memory.)
I'm not sure if I have the best method here, however what I would do, is store each value from the array into one large 1D array, sort that and then assign them to the 2D array.
int Sort2DArray(int A[][COL], unsigned int rowsize, unsigned int colsize)
{
int arraySize = rowsize * colsize;
int sortingArray[arraySize];
int i = 0, row, col, temp, prevPos;
//Fills the sortingArray with all the values in the 2D array
for (col = 0; col < colsize; ++col) {
for (row = 0; row < rowsize; ++row) {
sortingArray[i] = A[row][col];
++i;
}
}
//Sorts the 1D array (Insertion Sort)
for (i = 1; i < arraySize; ++i)
{
temp = sortingArray[i];
prevPos = i - 1;
while (j >= 0 && sortingArray[prevPos] > temp)
{
sortingArray[prevPos+1] = sortingArray[prevPos];
prevPos = prevPos - 1;
}
sortingArray[prevPos + 1] = temp;
}
//Writes data back into 2D array
i = 0;
for (row = 0; row < rowsize; ++row) {
for (col = 0; col < colsize; ++col) {
A[row][col] = sortingArray[i];
++i;
}
}
}
I hope I didn't get too confusing with all those dimensions, but you get the idea. If you spot anything incorrect, let me know.
It smells like homework to me, thus, I will only help you a little, and leave the rest to yourself.
When I was very new to C, and my first programming language, I had solved a lot of problems, and one of them was this.
The code I am pasting here is taken from here, a website, which I used to use a lot.
It is up to you to understand the algorithm, and program, and use it in your program.
#include<stdio.h>
int main( )
{
int a[][6]={
{25,64,96,32,78,27}, //Desired solution : {25,27,32,64,78,96},
{50,12,69,78,32,92} // {50,92,78,12,32,69}
};
int i, j, k, temp, temp1 ;
//Bubble sorting is applieed on one first row while the other row is swapped
for(j=1;j<6;j++)
{
for(i=0; i<5; i++)
{
if(a[0][i]>a[0][i+1])
{
temp=a[0][i];
a[0][i]=a[0][i+1];
a[0][i+1]=temp;
temp1 = a[1][i];
a[1][i] = a[1][i+1];
a[1][i+1]=temp1;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <2; i++ )
{
for(j=0; j<6; j++)
{
printf ( "%d\t", a[i][j] ) ; //printing sorted array
}
printf("\n");
}
}
It is a bit different from the code on the site, as I used to always used to work in Ubuntu, and linux never had conio.h. Also, if you are angry for me only providing the code used everywhere, and not doing all your work, keep in mind that homework assignments are for making the student think, and if I spoon-feed you, the purpose will be lost.
NOTE: Always post your full code which can be compiled successfully, as the code you have posted does not compile, as you have not declared all your functions. Thus, it is very difficult to understand you code.
Also, do not try to fool us, as the input you have mentioned does not have a 6, and you want a 6 also to be returned so actually even you have not compiled your code.
Here is a segment of my (incomplete) code
int rows(int board[][9]){
int badUnits = 0, i = 0, n = 9, j, z = 0;
int (*temp)[9];
//Sort each row of 2d array
for (z; z < n; z++){
for (i; i < n; i++){
for (j = i; j < n; j++){
if (board[z][i] > board[z][j]){
temp = board[z][i];
board[z][i] = board[z][j];
board[z][j] = temp;
}
}
}
}
printf ("%d\n", temp[1][0]);
printf ("%d\n", temp[1][1]);
return badUnits;
}
The function takes a 9*9 array.
I get a segmentation fault when the print statements are executed.
I believe my sort code is correct because it is similar to what I use for 1d arrays and I think everything else is correctly assigned.
So the culprit would be my temp variable. I have gone through and tried to assign values to it, tried to change the type, and have taken into account that the 2d array decays into a pointer but is not actually a pointer.
The conclusion I am left with is that this is a dynamic allocation issue. Can someone please lend a hand and assist me in fixing this? I have exhausted my knowledge base and am stuck.
To clarify: I decided to print the temp variable because I thought it would lend some information. The main problem was that the swap was not working, and I was still left with an unsorted array when I originally attempted to print out the board[][]. I know that board is what I am SUPPOSED to be printing.
Thank you for any help!
You assign an int value to temp
temp = board[z][i]; // Temp now is a what ever value was at
// That location in the array e.g. 42
You then treat temp as if it was the address in memory of an integer array
temp[1][1] // treat temp as a pointer and find the integer
// 10 integers further along then temp.
Also sometime temp will not have been initialised (never assigned to) in this case your going to get unexpected behaviour depending on what the last value stored where temp is now (Lets call it a random number).
Did you mean to output the values in board?
printf ("%d\n", board[1][0]);
printf ("%d\n", board[1][1]);
One thing to notice is that the variable temp will only get assigned to if a swap occurs, if the sorting algorithm was correct that is still a situation that could occur with a input corresponding to a sorted board.
But more importantly, the variable temp is used as an int during the swap. Later that integer value is interpreted as a pointer in the expressions temp[1][0] and temp[1][1], which in all likelihoods is not a valid address. You may want to change temp to be declared as:
int temp;
And figure out exactly what you would like to print. If it is whatever one of the two swapped values was (for the last swapped pair in the loop), then you would print it as:
printf("%d", temp);
Else, you would have to add logic according to what you really want to do.
Note that a single pass of this algorithm would not perform a complete sort, but I guess that's one of the reason why you said the provided code was not complete.
Something like this?
#include <stdio.h>
#include <stdlib.h>
void printArray(int** arr, int w, int h) {
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void sortArray(int** arr, int w, int h) {
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
for (int i = 0; i < w; ++i) {
if (arr[row][i] > arr[row][col]) {
int tmp = arr[row][col];
arr[row][col] = arr[row][i];
arr[row][i] = tmp;
}
}
}
}
}
int main() {
int w = 9, h = 9;
int** arr = (int**)malloc(sizeof(int*) * w);
for (int i = 0; i < w; ++i) {
arr[i] = (int*)malloc(sizeof(int) * h);
for (int j = 0; j < h; ++j) {
arr[i][j] = rand() % 10;
}
}
printf("Unsorted:\n");
printArray(arr, w, h);
sortArray(arr, w, h);
printf("Sorted:\n");
printArray(arr, w, h);
for (int j = 0; j < h; ++j) {
free(arr[j]);
}
free(arr);
return 0;
}