Why did my array get transposed? - c

I want declare a 2D array of doubles (double** data). I want to pass this by address to a helper function; so I pass &data and the helper function has argument double*** d.
Passed this way, the indexing that I used for the 2D array in the main function is no longer working.
Test code:
#include <stdio.h>
#include <stdlib.h>
void helperfunction(double*** data, int n, int c) {
printf("\nIn helper function\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < c; j++) {
printf("(%i %i %lf) ", i, j, *data[i][j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int n = 4; //number of rows
int c = 4; //number of columns
double count = 0.0;
double** data = malloc(n * sizeof(double*));
for (int i = 0; i < n; i++) {
double* row = malloc(c * sizeof(double));
for (int j = 0; j < c; j++) {
row[j] = count;
count += 1.2;
}
data[i] = row;
}
printf("In main function\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < c; j++) {
printf("(%i %i %lf) ", i, j, data[i][j]);
}
printf("\n");
}
helperfunction(&data, n, c);
return 0;
}
Output:
In main function
(0 0 0.000000) (0 1 1.200000) (0 2 2.400000) (0 3 3.600000)
(1 0 4.800000) (1 1 6.000000) (1 2 7.200000) (1 3 8.400000)
(2 0 9.600000) (2 1 10.800000) (2 2 12.000000) (2 3 13.200000)
(3 0 14.400000) (3 1 15.600000) (3 2 16.800000) (3 3 18.000000)
In helper function
(0 0 0.000000) (0 1 4.800000) (0 2 9.600000) (0 3 14.400000)
Segmentation fault (core dumped)
Obviously, something is wrong with the indexing when I deference the address (*data[i][j]) in the helper function. What is causing this?

*data[i][j] does not do what you think. It is equivalent to *(data[i][j]). Your options are:
Use (*data)[i][j] instead, or
Pass data (instead of &data) and use data[i][j] since passing a triple pointer isn't necessary here.

Sorry, just figured this out. The dereferencing using [] occurs before the deferencing using *. Therefore a call to *data[i][j] will cause the segmentation fault when i != 0, since the highest level pointer is only pointing to one thing, while the two lover levels of pointers point to arrays.
A solution is to use data[0][i][j] instead.

Related

Trying to get difference of 2 2D arrays using pointers

I am trying to create a subtract function using pointers for 2d array but when I run it I get
expression must have pointer-to-object type but it has type "int"C/C++(142)
Can anybody explain why i'm getting this error and what is a better way around this?
this is my code
Function to read array
int *readMatrix(int *arr)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
printf("row %d, col %d: ", i + 1, j + 1);
scanf("%d", &arr[i * 4 + j]);
}
}
printf("\n");
return arr;
}
Function to subtract 2 2d arrays
int *subM(int *arrA, int*arrB, int *arrC){
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
//printf("row %d, col %d: ", i + 1, j + 1);
&arrC[i][j] = &arrA[i][j] - &arrB[i][j]; //code where I am getting error
}
}
return arrC;
}
Main Function
int main()
{
int arrA[3][4];
int arrB[3][4];
int arrC[3][4];
readMatrix(&arrA[3][4]);
readMatrix(&arrB[3][4]);
subM(&arrA[3][4],&arrB[3][4],&arrC[3][4]);
return 0;
}
I am new to StackOverflow. I'm sorry if I can't express myself that well, but I think I found the solution to your problem.
Let's look at this step-by-step.
When passing an array to a function, you do not need to write the subscripts.
That means that instead of this:
readMatrix(&arrA[3][4]);
Just write this:
readMatrix(arrA);
You can (actually, should) also remove the pointer operator (&) because when only the array name is used, it acts as a pointer automatically.
Let's now take a look at the definition of readMatrix.
int *readMatrix(int *arr)
Using pointers for multi-dimensional arrays is okay, but the compiler would spit out a lot of warnings.
The most standard way is using subscripts in the definition of the function:
int *readMatrixStandard(int arr[3][4])
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
printf("row %d, col %d: ", i + 1, j + 1);
scanf("%d", &arr[i][j]);
}
}
printf("\n");
return arr;
}
The subscripts in subM
For your case, there are two ways to access a multi-dimensional array.
Either tell the compiler that this function takes an multi-dimensional array:
Instead of this:
int *subM(int *arrA, int*arrB, int *arrC)...
Do this:
int *subM(int arrA[3][4], int arrB[3][4], int arrC[3][4])...
The code would then look something like this:
int *subMMultiDimension(int arrA[3][4], int arrB[3][4], int arrC[3][4]){
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
//printf("row %d, col %d: ", i + 1, j + 1);
arrC[i][j] = arrA[i][j] - arrB[i][j]; //code where I am getting error
printf("%5d", arrC[i][j]);
}
puts(""); // for newline
}
return arrC;
}
Or use some pointer magic that is exclusive to C/C++ :) (not to be combined with the solution above)
Instead of this:
int *subM(int *arrA, int*arrB, int *arrC){
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
//printf("row %d, col %d: ", i + 1, j + 1);
&arrC[i][j] = &arrA[i][j] - &arrB[i][j]; //code where I am getting error
}
}
return arrC;
}
Try this:
int *subM(int *arrA, int *arrB, int *arrC){
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
//printf("row %d, col %d: ", i + 1, j + 1);
arrC[i * 4 + j] = arrA[i * 4 + j] - arrB[i * 4 + j]; //code where I am getting error
}
}
return arrC;
}
Use one of the ways, but the first one seems to be more standard because the compiler doesn't throw warnings on the first one.
Return value
You probably see where this is going. I'm just slapping on the code now.
Instead of:
return arr;
return arrC;
I prefer this for less warnings:
return arr[0];
return arrC[0];
The reason is simple. It points pratically to the same address, but it lets the compiler keep the mouth shut.
I think that this was it. The final code would look like this:
#include <stdio.h>
int * readMatrixStandard(int arr[3][4])
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
printf("row %d, col %d: ", i + 1, j + 1);
scanf("%d", &arr[i][j]);
}
}
printf("\n");
return arr[0];
}
int * subMMultiDimension(int arrA[3][4], int arrB[3][4], int arrC[3][4])
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
//printf("row %d, col %d: ", i + 1, j + 1);
arrC[i][j] = arrA[i][j] - arrB[i][j]; //code where I am getting error
printf("%5d", arrC[i][j]);
}
puts(""); // for newline
}
return arrC[0];
}
int main(void) // I recommend to always write void here if you are not using
// an old compiler
{
int arrA[3][4];
int arrB[3][4];
int arrC[3][4];
readMatrixStandard(arrA);
readMatrixStandard(arrB);
subMMultiDimension(arrA,arrB,arrC);
return 0;
}
Compiles nicely without warnings.
These code snippets are just my recommendations. If you want to know the most standard way to do something in C, you will probably have to look it up. A good book is also recommended. For instance, I learnt C with C Primer Plus by Stephen Prata. A great book with a lot of examples and illustrations to help you understand the situation.
Sorry again for my English. Guess there is still a long way to go.
If I missed anything or made a mistake somewhere, please let me know.
Edit: It's Stephen Prata, not Stephan ;)
By definition of the subscript operator [], the expression
A[B]
is equivalent to:
*(A + B)
Therefore,
A[B][C]
is equivalent to:
*( *(A+B) + C )
If you apply this to the line
&arrC[i][j] = &arrA[i][j] - &arrB[i][j];
it is equivalent to:
&*( *(arrC+i) + j ) = &*( *(arrA+i) + j ) - &*( *(arrB+i) + j );
The expression
&*( *(arrC+i) + j ) )
is invalid, for the following reason:
The sub-expression
*(arrC+i)
has type int, because dereferencing an int * yields an int. Therefore, the sub-expression
*(arrC+i) + j
will also evaluate to an int.
After evaluation that sub-expression, you then attempt to dereference that int using the * operator, which is illegal. Only pointer types can be dereferenced.
The sub-expressions
*( *(arrA+i) + j )
and
*( *(arrB+i) + j )
have exactly the same problem. You are also dereferencing an int in both of these expressions.
The actual problem is that you declared the function subM with the following parameters:
int *subM(int *arrA, int *arrB, int *arrC)
In C, arrays are usually passed to functions by passing a (possibly decayed) pointer to the first element of the (outer) array.
The parameter type int * would therefore be correct if you were passing 1D arrays to the function, but it is incorrect for 2D arrays. This is because a pointer to the first element of the outer array of a 2D int array has the type int (*)[4] in your case, i.e. a pointer to a 1D array of 4 int elements. However, you are instead passing a pointer to a single int object (not an array), so you are passing the wrong type of pointer.
Therefore, you should change the parameter types to the following:
int *subM( int (*arrA)[4], int (*arrB)[4], int (*arrC)[4] )
It may be clearer to write this the following way:
int *subM( int arrA[3][4], int arrB[3][4], int arrC[3][4] )
Both lines are equivalent, because arrays decay to pointers when used as function parameters.
Also, you should change the way you are calling the function. You should change the line
subM(&arrA[3][4],&arrB[3][4],&arrC[3][4]);
to:
subM( arrA[3], arrB[3], arrC[3] );
Due to array to pointer decay, this line is equivalent to:
subM( &arrA[3][0], &arrB[3][0], &arrC[3][0] );
Several issues ...
readMatrix uses an int *arr arg [correctly]. But, we want this to be compatible with sumM
sumM uses int * args, but tries to use dereference them using 2D array syntax.
In sumM, using (e.g.) &arr[i][j] is the address of the element and not its value [which is what we want].
In main, we're passing (e.g.) &arr[3][4]. This points past the end of the array, so this is UB (undefined behavior). We want to pass the start address of the array (e.g. arr or &arr[0][0]).
No need to pass back pointers to the resultant arrays because the caller passes in the addresses as args.
Here is the refactored code. It is annotated:
#include <stdio.h>
// Function to read array
#if 0
int *
readMatrix(int *arr)
#else
void
readMatrix(int arr[3][4])
#endif
{
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
printf("row %d, col %d: ", i + 1, j + 1);
#if 0
scanf("%d", &arr[i * 4 + j]);
#else
scanf("%d", &arr[i][j]);
#endif
}
}
printf("\n");
#if 0
return arr;
#endif
}
// Function to subtract 2 2d arrays
#if 0
int *
subM(int *arrA, int *arrB, int *arrC)
#else
void
subM(int arrA[3][4], int arrB[3][4], int arrC[3][4])
#endif
{
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
// printf("row %d, col %d: ", i + 1, j + 1);
// NOTE/BUG: we want to use the _values_ and _not_ the _addresses_ of the
// array elements
#if 0
&arrC[i][j] = &arrA[i][j] - &arrB[i][j];
#else
arrC[i][j] = arrA[i][j] - arrB[i][j];
#endif
}
}
// NOTE/BUG: since caller passed in the array, it knows where it is
#if 0
return arrC;
#endif
}
// Main Function
int
main(void)
{
int arrA[3][4];
int arrB[3][4];
int arrC[3][4];
// NOTE/BUG: doing (e.g.) &arrA[3][4] points past the _end_ of the 2D array
// and, so, is UB (undefined behavior) -- we want to pass the start address
#if 0
readMatrix(&arrA[3][4]);
readMatrix(&arrB[3][4]);
subM(&arrA[3][4], &arrB[3][4], &arrC[3][4]);
#else
readMatrix(arrA);
readMatrix(arrB);
subM(arrA, arrB, arrC);
#endif
return 0;
}
In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k

Snake sort a 2D array with pointers

I'm bad at C pointers, I'm not sure how should I sort the whole array, the code below sorted the array row-wise only, with a warning "assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]". This code sure works in Windows, not sure for other OSes. I am supposed to create a function called snake with 2D const int pointer array, and its size, m as inputs. I am not allowed to move or swap the contents within the array to be scanned, also the whole main function is not allowed to be edited. For example, the input for the whole program is
3
9 8 7
5 4 6
3 2 1
The correct output should be
1 2 3
6 5 4
7 8 9
Instead, I got this
7 8 9
4 5 6
1 2 3
And here is my code. There is a commented section in snake() because the assert function will fail if I uncomment it. I was trying to reverse the even rows (but the index starts from 0, so you can say odd rows also) after sorting.
#include <stdio.h>
#include <assert.h>
void snake(const int *ptr_array[100][100], int m){
int* p =NULL;
int temp;
for(int y=0;y<m;y++){
for(int k=0;k<m-1;k++){
for(int g=0;g<m-k-1;g++){
if(*ptr_array[y][g]>*ptr_array[y][g+1]){
p=(ptr_array[y][g]);
(ptr_array[y][g])=(ptr_array[y][g+1]);
(ptr_array[y][g+1]) = p;
}
}
}
}
// for(int h=1;h<m;h+=2){
// for(int g=0;g<m/2;g++){
// p = (ptr_array[h][m-g]);
// (ptr_array[h][m-g]) = (ptr_array[h][g]);
// (ptr_array[h][g]) = p;
// }
// }
}
int main()
{
int array[100][100], check[100][100];
const int *ptr_array[100][100];
int i, j, m;
scanf("%d", &m);
for (i = 0; i < m; i++){
for (j = 0; j < m; j++) {
ptr_array[i][j] = &(array[i][j]);
scanf("%d", &(array[i][j]));
check[i][j] = array[i][j];
}
}
snake(ptr_array, m);
for (i = 0; i < m; i++) {
for (j = 0; j < m; j++) {
assert(check[i][j] == array[i][j]);
assert((ptr_array[i][j] >= &array[0][0]) && (ptr_array[i][j] <= &array[99][99]));
printf("%d ", *(ptr_array[i][j]));
}
printf("\n");
}
return 0;
}
#include <stdio.h>
void snake(const int *ptr_array[100][100], int m){
int* p =NULL;
int* w=NULL;
int temp,l;
for(int y=0;y<m;y++){
for(int k=0;k<m;k++){
p = ptr_array[y][k];
l = k+1;
for(int g=y;g<m;g++){
while(l<m){
if(*p>*ptr_array[g][l]){
p=(ptr_array[g][l]);
(ptr_array[g][l])=(ptr_array[y][k]);
(ptr_array[y][k]) = p;
}
l++;
}
l=0;
}
}
}
for(int h=1;h<m;h+=2){
for(int g=0;g<=(m-1)/2;g++){
w = (ptr_array[h][m-1-g]);
(ptr_array[h][m-1-g]) = (ptr_array[h][g]);
(ptr_array[h][g]) = w;
}
}
}

2D arrays using arrays of pointers or pointers to pointers in C?

I'm writing a C for which I need to create a 2D array. I've found a solution to my problem using double pointers (pointers to pointers) in the following way:
#include <stdio.h>
#include <stdlib.h>
int d = 3;
#define DIM_MAX 9
void changeArray(int d, int *array[d]);
int main()
{
//alocate array of 'd' colummns and 'd' row using malloc using array of pointers
int **array = malloc(d*sizeof(int *));
for(int count = 0; count < d; count++)
{
array[count] = malloc(d*sizeof(int *));
}
/* Call changeArray function */
changeArray(d, array);
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
for(int count = 0; count < d; count++)
{
free(array[count]);
}
return 0;
}
void changeArray(int n, int *array[d])
{
for(int i =0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
array[i][j] = i*j;
}
}
return;
}
The code above works pretty well (it seems), but I've read in the web that using pointer to pointer is not the correct way to create 2D arrays. So I've come up with the following code, which also works:
#include <stdio.h>
#include <stdlib.h>
#define DIM_MAX 9
int d = 3;
void changeArray(int d, int *array[d]);
int main()
{
//alocate array of 'd' colummns and 'd' row using malloc using array of pointers
int *array[DIM_MAX] = {0};
for(int count = 0; count < d; count++)
{
array[count] = (int *)malloc(d*sizeof(int *));
}
/* Call changeArray function */
changeArray(d, array);
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
for(int count = 0; count < d; count++)
{
free(array[count]);
}
return 0;
}
void changeArray(int n, int *array[d])
{
for(int i =0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
array[i][j] = i*j;
}
}
return;
}
What is the difference in using any of the two ways above to write this code?
[Not an answer, but an alternative approach to achieve the desired result, namely defining a user-defined 2D array.]
Assuming the compiler in use supports VLAs you could do this:
#include <stddef.h> /* for size_t */
void init_a(size_t x, size_t y, int a[x][y]); /* Order matters here!
1st give the dimensions, then the array. */
{
for (size_t i = 0; i < x; ++i)
{
for (size_t j = 0; j < y; ++j)
{
a[i][j] = (int) (i * j); /* or whatever values you need ... */
}
}
}
int main(void)
{
size_t x, y;
/* Read in x and y from where ever ... */
{
int a[x][y]; /* Define array of user specified size. */
init_a(x, y, a); /* "Initialise" the array's elements. */
...
}
}
It is actually pretty simple. All you have to do is this:
int i[][];
You are overthinking it. Same as a normal array, but has two indexes.
Let's say you want to create a "table" of 4 x 4. You will need to malloc space for 4 pointers, first. Each of those index points will contain a pointer which references the location in memory where your [sub] array begins (in this case, let's say the first pointer points to the location in memory where your first of four arrays is). Now this array needs to be malloc for 4 "spaces" (in this case, let's assume of type INT). (so array[0] = the first array) If you wanted to set the values 1, 2, 3, 4 within that array, you'd be specifying array[0][0], array[0][1], array[0][2], array[0][3]. This would then be repeated for the other 3 arrays that create this table.
Hope this helps!

C: Overwrite Array2D values not working when using function

I want max to have the content of tmp_max. max is dynamically allocated. tmp_max size is known.
Copying the values is working correctly when I hardcode it but it doesn't work when I create a function to copy the values. Why is that?
//This code works
int** max;
init2D(&max,3,4);
int tmp_max[3][4] = {{3,3,2,2}, {1,2,3,4}, {1,3,5,0}};
for(int i = 0 ; i < 3; i++)
for(int j = 0 ; j < 4; j++)
max[i][j] = tmp_max[i][j];
assert(max[0][1] == 3);
//This one crashes
void copyArray2D(int a, int b, int*** tab,int*** tab2){
for(int i = 0 ; i < a; i++)
for(int j = 0 ; j < b; j++)
tab2[i][j] = tab[i][j];
}
int** max;
init2D(&max,3,4);
int tmp_max[3][4] = {{3,3,2,2}, {1,2,3,4}, {1,3,5,0}};
copyArray2D(3,4,&tmp_max,&max); //crash
assert(max[0][1] == 3);
Note:
Using void copyArray2D(int a, int b, int** tab,int** tab2){and copyArray2D(3,4,max,tmp_max); isn't working either.
Using void copyArray2D(int a, int b, int** tab,int** tab2){and copyArray2D(3,4,&max,&tmp_max); isn't working either.
void init2D(int ***data_ptr, int x, int y) {
int **data = (int **) malloc(sizeof(int *) * x);
for (int k = 0; k < x; k++)
data[k] = (int *) malloc(sizeof(int) * y);
*data_ptr = data;
}
Your compiler should complain about copyArray2D(3,4,&tmp_max,&max).
You must fix any issues identified by your compiler before trying to run your code (running any such executable based on broken code is meaningless).
One problem is that copyArray2D says int*** when it should say int**.
After fixing that, the main issue here is that you have written copyArray2D so that it only works with an array of pointers. (You are simulating a 2-D array by allocating an array of pointers, and then making each pointer point to a separate allocation representing each row).
This works when you use init2D because the init2D function allocates an array of pointers etc.
However int tmp_max[3][4] is a block of 12 contiguous ints. There are no pointers. This is not compatible with copyArray2D.
Your options are:
Use int **tmp_max and use init2D to allocate it, instead of int tmp_max[3][4]
Make another version of copyArray2D which works on a contiguous 2-D array.
Use an ugly macro
Your second function has too many stars. You hadn't shown the init2D function when I first wrote an answer, so I had to guess what you'd done with that (but the code is now in the question and is close enough to what I produced that the difference is immaterial — except I do error check the allocations). Here's a (rewritten) version of the code (the first version hadn't been near a compiler, and I completely missed a crucial detail). Note that int ** is not the same as int arr[N][M] or variations on the theme — even if you use the same notation to access both.
#include <stdio.h>
#include <stdlib.h>
static void copyArray2D(int a, int b, int **dst, int src[a][b])
{
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
dst[i][j] = src[i][j];
}
static void oom(void)
{
fprintf(stderr, "Out of memory\n");
exit(1);
}
static void init2D(int ***arr, int a, int b)
{
(*arr) = malloc(a * sizeof((*arr)[0]));
if (*arr == 0)
oom();
for (int i = 0; i < a; i++)
{
(*arr)[i] = malloc(b * sizeof((*arr)[0][0]));
if ((*arr)[i] == 0)
oom();
}
}
static void dump_2d_array(int a, int b, int arr[a][b])
{
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
printf(" %2d", arr[i][j]);
putchar('\n');
}
}
static void dump_2d_pointers(int a, int b, int **arr)
{
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
printf(" %2d", arr[i][j]);
putchar('\n');
}
}
int main(void)
{
int **max;
init2D(&max, 3, 4);
int tmp_max[3][4] = { { 3, 3, 2, 2 }, { 1, 2, 3, 4 }, { 1, 3, 5, 0 } };
copyArray2D(3, 4, max, tmp_max);
printf("2D array:\n");
dump_2d_array(3, 4, tmp_max);
printf("List of pointers:\n");
dump_2d_pointers(3, 4, max);
return 0;
}
Output from running that code:
2D array:
3 3 2 2
1 2 3 4
1 3 5 0
List of pointers:
3 3 2 2
1 2 3 4
1 3 5 0
Note that I've not written a free function, so the memory is leaked.
Be wary of 3-Star Programming.
void copyArray2D(int a, int b, int tab[a][b],int*** tab2){
for(int i = 0 ; i < a; i++)
for(int j = 0 ; j < b; j++)
(*tab2)[i][j] = tab[i][j];
}
copyArray2D(3,4,tmp_max,&max);

Is it possible to sort in ascending order, a 2D array in C? If so, how?

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.

Resources