i have problem with the third function (GetMatrix) the others are works.
i want to catch data from user into the matrix by poiters only
the lines:
typedef int pArr[COLS];
void GetMatrix(pArr* ,int , int );
M[ROWS][COLS];
are constraints
how i need to do the scan, i try to use scanf("%d",*(M+cols*i+j))
but i get error..its probably wrong
what is need to do to make it right
thx all
the code :
#pragma warning ( disable: 4996 )
#include <stdio.h>
#include <string.h>
#define ROWS 2
#define COLS 3
typedef int pArr[COLS];
void MergeStrings(char* str1,char* str2,char* strRes);
void StrReverse(char* strRes,char* strRev);
void GetMatrix(pArr* M ,int rows , int cols);
void main()
{
char str1[256],str2[256],strRes[256],strRev[256];
int M[ROWS][COLS];
printf("Please enter first string:\n");
flushall();
gets(str1);
printf("\nPlease enter second string:\n");
flushall();
gets(str2);
printf("\nMerge of: %s\n",str1);
printf("with: %s\n",str2);
MergeStrings(str1,str2,strRes);
StrReverse(strRes,strRev);
printf("is:\n");
printf("==> %s\n",strRes);
printf("\nthe reversed merged string is:\n");
printf("==> %s\n\n",strRev);
GetMatrix(M,ROWS,COLS);
}
void MergeStrings(char* str1,char* str2,char* strRes)
{
int i=0,j=0,a=0,flag=0,flag2=0;
do
{
while( *(str1+i)==' ')
i++;
while( *(str2+j)==' ')
j++;
while( *(str1+i)!=' ' && *(str1+i)!='\0')
{
*(strRes+a)=*(str1+i);
i++;
a++;
}
if(flag!=1)
{
*(strRes+a)=' ';
a++;
}
if(*(str1+i)=='\0')
flag=1;
while( *(str2+j)!=' ' && *(str2+j)!='\0')
{
*(strRes+a)=*(str2+j);
j++;
a++;
}
if(flag2!=1)
{
*(strRes+a)=' ';
a++;
}
if(*(str2+j)=='\0')
flag2=1;
}while( (*(str1+i)!='\0') || (*(str2+j)!='\0') );
*(strRes+a)='\0';
}
void StrReverse(char* strRes,char* strRev)
{
int size,i=0,j=0;
size=strlen(strRes);
for(i=size-2 ; i>=0 ;i--)
{
*(strRev+j)=*(strRes+i);
j++;
}
*(strRev+size-1)='\0';
}
void GetMatrix(pArr* M ,int rows , int cols )
{
}
do you mean?
int GetMatrix( pArr* M ,int rows , int cols )
{
return 1==scanf("%d",&M[rows][cols]);
}
#define ROWS 2
#define COLS 3
typedef int pArr[COLS];
void GetMatrix(pArr* M ,int rows , int cols )
{
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
scanf("%d", &(M[i][j]));
}
int main()
{
int M[ROWS][COLS] = {{100, 101, 102},{103, 104, 105}};
printf("before\n");
for(int i = 0; i < ROWS; i++){
for(int j = 0; j < COLS; j++)
printf("%d ", M[i][j]);
printf("\n");
}
printf("enter values\n");
GetMatrix(M, ROWS, COLS);
printf("after\n");
for(int i = 0; i < ROWS; i++){
for(int j = 0; j < COLS; j++)
printf("%d ", M[i][j]);
printf("\n");
}
}
Output:
before
100 101 102
103 104 105
enter values
0 1 2 3 4 5
after
0 1 2
3 4 5
Inside the function, M is a pointer to an array of three integers. M[i] is the i-th array, and M[i][j] is the j-th element in the i-th array. & operator gives its address to the scanf, which happily stores the read number in there.
Here is what happens when you replace scanf("%d", &(M[i][j])); with scanf("%d",*(M+cols*i+j)):
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
scanf("%d", *(M + cols * i + j));
snip..
before
100 101 102
103 104 105
enter values
0 1 2 3 4 5
after
0 101 102
1 104 105
In the first iteration of the inner loop, i and j are zero, and *(M+cols*i+j) becomes *M. Since M is a pointer to an array, dereferencing it gives you an array of integers which decays into pointer to an integer. Thus the first number get stored at the correct place.
In the second iteration of the inner loop, j is 1. Thus, it is *(M + 1). Pointer arithmetic comes into picture here. Since M is a pointer to an array of three integers, (M + 1) is a pointer to an array of three integers that points to the second array; dereferencing it gives the array, which decays into pointer and scanf writes the second number there.
In the third iteration, j is 2 and (M + 2) points to the third (non existent) array and scanf writes the entered number into that memory location in the stack, thus corrupting the stack.
So on and so forth. It attempts to write into every third integer location, leaving our preinitialized values (101, 102, 104, 105) untouched.
If you want to it with pointers, you can cast M as a pointer to int as in:
scanf("%d", (int*)M + cols * i + j);
Once you cast M as int*, pointer arithmetic adds 1 * sizeof(int) to the starting position instead of 1 * sizeof(array of three ints), thus giving the desired results.
Update - answer to the comment I received in Facebook.
Consider the snippet:
int a = 10;
scanf("%d", &a);
printf("%d", a);
Scanf stores the entered value at the specified address - hence we pass a pointer to int as its argument. printf prints the passed value - hence we pass an int as the argument. The same difference applies here. ((int*)M + cols * i + j) is of type int*, pointer to an integer. To print the integer at that location we should dereference it using * operator. Thus it becomes:
printf("%d\t",*((int*)M + cols * i + j));
Oh, and by the way, you'd have received a faster reply if you had posted your doubts here itself instead of my FB. There are lots of good people ready to help hanging out in SO - and I check FB only on weekends.
Related
I tried implemented matrix struct in C, ( generate and show that ). I don't have a trouble with generate but i discovered something I didn't understand. When i uncomment printf("\n") i don't get variable from matrix but whith commented printf("\n") everything working correct. It's not a big problem but I'm curious why this happen. It's looks like printf has destructed my structure.
void show_matrix(struct matrix matrix1){
for(int i =0; i < matrix1.number_of_row; i++){
for(int j = 0; j <matrix1.number_of_columns; j++){
printf("%d " , matrix1.variable[i * matrix1.number_of_columns + j]);
}
// printf("\n");
}
}
Here is my main :
#include <stdio.h>
#include "matrix_operations.h"
int main(){
int columns;
int rows;
printf("Enter the number of columns \n");
scanf("%d",&columns);
printf("Enter the number of rows \n");
scanf("%d", &rows);
struct matrix matrix1;
matrix1 = generate_matrix(columns,rows);
show_matrix(matrix1);
return 0;
}
Here is my file matrix_operations.h :
#include "matrix.h"
#include <stdlib.h>
struct matrix generate_matrix(int columns, int rows){
int value;
struct matrix matrix1;
matrix1.number_of_columns = columns;
matrix1.number_of_row = rows;
int values[rows * columns];
matrix1.variable = values;
for(int i = 0 ; i < rows ; i++){
for(int j =0 ; j <columns ; j++){
value = random() %2;
matrix1.variable[i * columns +j] = value;
/* Uncomment to see generated matrix
printf("%d ", matrix1.values[ i * columns +j]);
*/
}
/* Uncomment to see generated matrix
printf("\n");
*/
}
return matrix1;
}
void show_matrix(struct matrix matrix1){
for(int i =0; i < matrix1.number_of_row; i++){
for(int j = 0; j <matrix1.number_of_columns; j++){
printf("%d " , matrix1.variable[i * matrix1.number_of_columns + j]);
}
/* Uncomment to not working correctly
printf("\n");
*/
}
}
Here is my struct in file matrix.h :
struct matrix{
int number_of_columns;
int number_of_row;
int *variable;
};
Sample input :
4
4
Sample output with commented printf (16 random numbers 0 or 1):
1 0 1 1 0 0 1 1 0 0 1 1 0 1 0 1
Sample output with uncommented printf
1 0 1 1
-2051332800 32571 0 0
0 0 -2053095405 32571
-2051684704 32571 10 0
The problem is that generate_matrix returns a struct matrix with a variable field that points at a local variable (values) of the function. This goes out of scope when the function returns, leaving you with a dangling pointer, and when you later dereference it, you get undefined behavior.
You need to ensure that this pointer points at something with sufficient lifetime to not become dangling. One way to do that would be to use malloc in the generate_matrix function rather than using a local variable:
int *values = malloc(rows * columns * sizeof(int));
This will allocate memory that lasts until you explicitly free it. Now you have the issue that you need to figure out when to free it (when you no longer need it), or you'll have a memory leak.
I am new to C programming and especially to pointers. In the program I wrote, I tried to write a function that returns a pointer to specified column of array. See the code below for better understanding (or confusion :) ):
#include <stdio.h>
#include <stdlib.h>
// function for getting pointer to specidifed column index
// 'ind' is index of requested column, 'ncol' is number of items in column
int* get_col(const int* arr, unsigned int ind, unsigned int ncol);
int main() {
unsigned int n;
printf("Input matrix size : ");
scanf("%i", &n);
int arr[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
arr[i][j] = i * n + j;
}
for (int i = 0; i < n; i++) {
printf("values in column %d: \n", i);
int *col = get_col((int*)arr, i, n);
for (int j = 0; j < n; j++) {
printf("%d ", *col);
col = col + 1;
}
printf("\n");
}
return 0;
}
int* get_col(const int* arr, unsigned int ind, unsigned int ncol) {
int *result = malloc(sizeof(int) * ncol);
for (int i = 0; i < ncol; i++)
*result = *(arr + i*ncol + ind);
return result;
}
As you see get_col function accepts pointer to array, column index and column size (n of elements in column, i.e number of rows) as arguments and trying to return a pointer to 1D array that contains values of column at requested index. The problem is that result is not correct. In case n=3 results are like below:
Input matrix size : 3
values in column 0:
6 0 0 // supposed to be 0 3 6
values in column 1:
7 0 0 // supposed to be 1 4 7
values in column 2:
8 0 0 // supposed to be 2 5 8
I think that the problem lies in my understanding of pointers not the algorithm implemented. Actually, at first I didn't use pointer in my get_col function like below:
int result[ncol];
// ... do my work here to populate array
return &result;
Then as compiler complains warning: function returns address of local variable [-Wreturn-local-addr], I converted result from array to pointer in get_col function like above. What is the problem in this code? Did I use pointers in get_col function as it should be?
In the following line:
*result = *(arr + i*ncol + ind);
You're always writing to the same memory address.
Change it to one of the two following options:
*(result + i) = *(arr + i*ncol + ind);
result[i] = *(arr + i*ncol + ind);
Regarding your second problem when you used:
int result[ncol];
// ... do my work here to populate array
return &result;
You should understand that result variable in this case (static-memory allocation) is stored in the stack. So, after your function returns, the variable values doesn't exist anymore in the memory. That's why you need dynamic-memory allocation. In dynamic-memory allocation, that values stay in the memory until you call free by yourself.
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.
I'm practicing pointers and want to substitute pointer operations in place of the arrays to traverse through the elements of the array. I have read numerous articles and cannot grasp this concept. Can someone explain?
Here I made a 2D array and iterated through it using a basic nested for-loop, but want to use pointers;
int test[3][2] = {1,4,2,5,2,8};
for (int i = 0 ; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d\n", test[i][j]);
}
}
int test[3][2] = {{1,4},{2,5},{2,8}};
// Define a pointer to walk the rows of the 2D array.
int (*p1)[2] = test;
// Define a pointer to walk the columns of each row of the 2D array.
int *p2 = NULL;
// There are three rows in the 2D array.
// p1 has been initialized to point to the first row of the 2D array.
// Make sure the iteration stops after the third row of the 2D array.
for (; p1 != test+3; ++p1) {
// Iterate over each column of the arrays.
// p2 is initialized to *p1, which points to the first column.
// Iteration must stop after two columns. Hence, the breaking
// condition of the loop is when p2 == *p1+2
for (p2 = *p1; p2 != *p1+2; ++p2 ) {
printf("%d\n", *p2);
}
}
In some compilers you can also use a single loop, treating a multidimensional array as a one-dimensional array read in row-major order.
This is mentioned in King's C Programming: A Modern Approach (2nd ed., p268).
#include <stdio.h>
int main(void)
{
int test[3][2] = {{1,4},{2,5},{2,8}}, *p;
for(p = &test[0][0]; p <= &test[2][1]; p++)
{
printf("%d\n", *p);
}
return 0;
}
Try the following and investigate
#include <stdio.h>
int main(void)
{
int test[3][2] = { { 1,4 }, { 2,5 }, { 2,8 } };
for ( int ( *p )[2] = test ; p != test + 3; ++p )
{
for ( int *q = *p; q != *p + 2; ++q ) printf( "%d ", *q );
puts( "" );
}
return 0;
}
The putput is
1 4
2 5
2 8
The first pointer is a pointer to an object of type int[2] that is it points to the first "row" of the array and then due to increments it points to other rows.. The second pointer is a pointer to an object of type int. It points to the first element of each row in the inner loop.
Treating a 2d array as 1d array is very easy using pointer arithmetic to iterate.
void print_2d_array(int *num, size) {
int counter = 0;
while (counter++ < size) {
printf("%i ", *num);
num++;
}
printf("\n");
}
int main() {
int matrix[2][3] = {{2, 11, 33},
{9, 8, 77}};
int matrix_size = sizeof(matrix) / sizeof(int); // 24 bytes / 4 (int size) = 6 itens
print_2d_array(matrix, matrix_size);
return 0;
}
If pointer declaration is the goal of your practice, use the following initialization:
int (*pTest)[rmax][cmax] = test;
Once you do that, the syntax of using pointer indexing mirrors that of array indexing, except that you have to use the * de-referencing operator.
for (int i= 0; i < 3; i++) {
for (int j= 0; j < 2; j++) {
printf ("%d ", *(pTest[i][j]));
}
printf ("\n");
}
However, if pointer arithmetic is the goal of your practice, then the following will work too:
int *res = &test;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf ("%d ", *(res + i*2 + j));
}
printf ("\n");
}
OUTPUT
1 4
2 5
2 8
I want to change rows into column and column into rows of that 2-D array
I want a program which takes input and gives output as below.
Input: 1 2 3
4 5 6
Output: 1 4
2 5
3 6
Input: 1 2 3
4 5 6
7 8 9
Output: 1 4 7
2 5 8
3 6 9
I did a sample which in hardcoded array as below
int main()
{
int i,j;
int grades[2][3] = { {55, 60, 65},
{85, 90, 95}
};
for( j = 0; j < 3; j++)
{
for( i = 0; i < 2;i++)
{
printf("%d\t",grades[i][j]);
}
printf("\n");
}
return 0;
}
Its long time since i programmed in C , is there anyway we can make things dynamic or better way of doing the same. Right now its hardcoded.
I remember we have to use malloc or so , is that right.
psuedo code is also fine.
Taking from Zhehao Mao user and fixing it, the would look like this:
#include <stdio.h>
void transpose(int *src, int *dest, int rows, int cols){
int i,j;
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
dest[j*rows + i] = src[i*cols + j];
}
}
}
int main(void)
{
int oldar[2][3] = {{1,2,3},{4,5,6}};
int newar[3][2];
transpose(&oldar[0][0], &newar[0][0], 2, 3);
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
printf("%d ", oldar[i][j]);
printf("\n");
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 2; j++)
printf("%d ", newar[i][j]);
printf("\n");
}
}
The reason the original post can't work is that int ** expects a pointer to pointers like:
int **a ---------> int *int1 --> 1
int *int2 --> 2
int *int3 --> 3
which is not what we get when we say int a[n][m]. Rather we have the array organized like this
a[0][0]
\
1 2 3 4 5 6
\___/ \___/
"a[0]" / \____ "a[1]"
or something like this. The picture likely does not explain it well, but currently I can't do better.
void main()
{
clrscr();
int in[10][10];
int out[10][10];
int row,column,i,j;
printf("enter row");
scanf("%d",&row);
printf("Enter column");
scanf("%d",&column);
//storing values in matrix
for(i=1;i<=row;i++)
{
for(j=1;j<=column;j++)
{
printf("Enter (%d,%d)th value",i,j);
scanf("%d",&in[i-1][j-1]);
}
}
//show stored values
printf("\ninput is\n\n");
for(i=0;i<row;i++)
{
for(j=0;j<column;j++)
{
printf("%d\t",in[i][j]);
}
printf("\n");
}
//show transposed value. it is also stored in out matrix
printf("\nOutput is\n\n");
for(i=0;i<column;i++)
{
for(j=0;j<row;j++)
{
printf("%d\t",in[j][i]);
out[i][j]=in[j][i];
}
printf("\n");
}
getch();
}
//////////////////////////////////////
input matrix is stored in in[][] matrix and output matrix stored in out[][] matrix.
this program will work for any matrix with row and column below 10 if we increase the matrix variable value ,it will work for larger matrix also .
Here is a rather naive implementation. I'm pretty sure there are more efficient ways, but this is all I could think of.
void transpose(int **src, int **dest, int rows, int cols){
int i,j;
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
dest[j][i] = src[i][j];
}
}
}
int main(void){
int oldar[2][3] = {{1,2,3},{4,5,6}};
int newar[3][2];
transpose(oldar, newar, 2, 3);
}
Double pointers can represent double arrays, so there is no need to allocate on the heap here.
This is a half-done program the way I would do it in C:
int main()
{
int **data;
int rows = 0,
columns = 0;
char in[256];
int *irow;
// Get user input.
for(rows = 0; 1; ++rows)
{
scanf("%255s", in);
if(strcmp(in, "exit") == 0)
break;
// Parse row here. Remove all the tabs. Set column count.
for(int icolumn = 0; 1; ++icolumn)
{
/* ... */
}
// Set columns if first time.
if(rows == 0)
columns = icolumn;
// Check to make sure user inputs correct amount of columns.
if(columns != icolumns)
{
printf("OMG! The user is a hacker!\n");
break;
}
// Push parsed row into **data.
data[rows] = irow;
}
// Display output.
for(int i = 0; i < columns; ++i)
{
for(int j = 0; j < rows; ++j)
{
printf("%d\t", data[j][i]);
}
printf("\n");
}
return 0;
}
I'm a C++ programmer, so the user input part is kind of messed up.
hey here is a simple solution without using malloc,i did this when i was on the 0th level for c and had no idea about "alloc.h" functions,
You can have the square array having #rows = #cols = max(#rows,#cols),if we take your example then the matrix would be a 3x3 matrix,then add any special char in the blank entries,so the matrix will look like this
matrix:1 2 3
4 5 6
# # #
now you can easily convert the matrix in the way you want...
Bottom line:To make the matrix operations simpler try to convert them in square matrix...
One more thing using MALLOC is the best possible way ,this is just in case you are not handy with all those alloc.h function defs...
theoretically, you have two arrays
Array x and y
Int grades [x] [y]
you can swap these two arrays and you get
int grades [y] [x]
to do that there are many methods e.g. by copying the arrays to another two 1D, or one 2D Array, or simple Pointer Swap