I am trying to use column major order to a 2d matrix which I am using as 1d.

 int N=3,R=2;
 for (int i=0;i<N;i++){
    for (int j=0;j<R;j++){

      //printf("\nX[%d]=%d\t",i+j*N,res[i+j*N]); //column major
     // printf("\nX[%d]=%d\t",i*R+j,res[i*R+j]); //row major


    }
    printf("\n");
  }

but the column major doesn not work as it should.

Also,if I want to substract only column elements from a matrix (2d which is used as 1d),how should I approach?
Because ,that's why I am trying to present my matrix as column major order and then use its columns.

Dani AI

Generated

Short diagnosis and what went wrong (two separate causes). First, the loop that tried to “store as column-major” by writing into the same buffer you read from corrupts values: some source elements are overwritten before you read them. Second, the multiplication code computes a matrix with one memory ordering (row-major) but you later print it as if it were stored in the other ordering (column-major). ’s print examples nicely show how the same bytes can be interpreted two different ways, and ’s C/C++ remark about allocation and style is a useful reminder.

Safe fix for conversion: don’t try to reorder in-place unless you use a correct in-place transpose algorithm (which is only straightforward for square matrices). Allocate a second buffer, copy with the proper index mapping, then replace or memcpy back. Example (m rows, n columns):

/* src is row-major (m x n). dst will be column-major. */
int *dst = malloc(m * n * sizeof *dst);
for (int r = 0; r < m; ++r)
  for (int c = 0; c < n; ++c)
    dst[c * m + r] = src[r * n + c];   /* column-major index = c*m + r */
memcpy(src, dst, m * n * sizeof *dst);
free(dst);

Keep storage and all indexing consistent during arithmetic. Either produce the product in row-major and print row-major, or compute directly into a column-major output buffer. For column-major multiplication (A is m×n, B is n×p, all column-major):

for (int j = 0; j < p; ++j)
  for (int i = 0; i < m; ++i) {
    int sum = 0;
    for (int k = 0; k < n; ++k)
      sum += A[i + k*m] * B[k + j*n];   /* read A,B in column-major */
    C[i + j*m] = sum;                   /* write C in column-major */
  }

Quick debugging tips: test with tiny matrices (2×3, 3×2) and print element indices as you copy; always initialize/zero result buffers; check malloc sizes with sizeof *ptr; prefer separate src/dst buffers when converting; and stick to one convention across compute/print. This will make the output predictable and fix the errors you saw.

Recommended Answers

All 6 Replies

#include <iostream>

void printrowmajor(int* arr, int width, int height)
{
    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
            std::cout<<arr[i * width + j]<<" ";

        std::cout<<"\n";
    }
}

void printcolumnmajor(int* arr, int width, int height)
{
    for (int i = 0; i < width; ++i)
    {
        for (int j = 0; j < height; ++j)
            std::cout<<arr[i + j * width]<<" ";

        std::cout<<"\n";
    }
}

int main()
{
    int arr[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

    printrowmajor(&arr[0], 4, 3);

    std::cout<<"\n";

    printcolumnmajor(&arr[0], 4, 3);
    return 0;
}

This will print:

0 1 2 3 
4 5 6 7 
8 9 10 11 

0 4 8 
1 5 9 
2 6 10 
3 7 11 

This.. will also print the same thing:

int main()
{
    int arr[3][4] =
    {
        {0, 1, 2, 3},
        {4, 5, 6, 7},
        {8, 9, 10, 11}
    };

    printrowmajor(&arr[0][0], 4, 3);

    std::cout<<"\n";

    printcolumnmajor(&arr[0][0], 4, 3);
    return 0;
}

I am using the right indices.

Can you tell me why these 2 things don't work?

1) I have 2 matrices ,I multiply them and I can printf as row major or column major (everything is fine until now).
Now,if I store the result matrix (which I received from multiplication) :

     ...
     //store as column major
       for (int i=0;i<rows;i++){
          for (int j=0;j<cols;j++){
           res[i+j*rows]=res[i*cols+j];

       }
       }

       for (int i=0;i<rows;i++){
           for (int j=0;j<cols;j++){


         printf("\nB[%d]=%d\t",i+j*rows,res[i+j*rows]);
           //printf("\nB[%d]=%d\t",i*cols+j,res[i*cols+j]);

        }

      }

then neither printf shows the right results.

2) Can you tell me why this doesn't show the right results for column major but only for row major?

    int main(int argc, const char* argv[]) {
      int rows=3;
      int cols=2;

      int *A=(int*)malloc(rows*rows*sizeof(int));
      int *B=(int*)malloc(rows*cols*sizeof(int));
      int *result=(int*)malloc(rows*cols*sizeof(int));

      A[0]=1;
      A[1]=2;
      A[2]=3;
      A[3]=4;
      A[4]=5;
      A[5]=6;
      A[6]=7;
      A[7]=8;
      A[8]=9;

      B[0]=5;
      B[1]=6;
      B[2]=7;
      B[3]=8;
      B[4]=4;
      B[5]=5;


     for (int i=0;i<rows;i++){
       for (int j=0;j<cols;j++){
         result[i*cols+j]=0;
         for (int k=0;k<rows;k++){
        result[i*cols+j]+=A[i*rows+k]*B[k*cols+j];

       }

       }
    }


      for (int i=0;i<rows;i++){
        for (int j=0;j<cols;j++){

         printf("\nB[%d]=%d\t",i+j*rows,result[i+j*rows]);  //column major

         //printf("\nB[%d]=%d\t",i*cols+j,result[i*cols+j]);  //row major


        }
        printf("\n");
      }


      return 0; 

     }

Hold on for a moment, here. Is this supposed to be a C++ program, or a C program? While most C code is also valid C++, as a rule in C++ you want to avoid using certain C idioms and functions, with malloc(), free() and the standard C I/O functions (e.g., printf()) near the top of the list. If you are writing a C program, it would be advisable to post your questions in the C forum, to avoid confusion.

On a related note, why are you allocating the arrays dynamically, when you are using fixed array sizes?

Yes, I am using C code and compile it as C.Sorry.
Ok, I missed that with the matrices.
I corrected to a fixed size but still the same problem.

Since you are coding ALL in C, why not start fresh in the C forum ... I think I have some ideas that you may find useful.

Ok, I posted here , thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.