Display struct variable with printf("\n") - arrays

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.

Related

C - Segmentation Fault Reading Struct and Dynamic2D Array Member

I just started learning C and I wanted to try creating a test program that works with pointers, structures, and arrays, since I still have a hard time understanding them. I created this test file which is a distilled version of a larger project that I'm working on. The test file has a struct with a dynamic 2D array as a member of the struct:
typedef struct {
int ** array;
int rows, cols;
} Smaller;
However, after running the test file the terminal returns the following error:
zsh: segmentation fault ./a.out
I researched what this error means,
" Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” " (Link)
But I'm still confused on how fix this problem. I'm pretty sure I allocated the correct amount of memory for each row and column. It's even more confusing because the terminal doesn't indicate which line the error is. I would appreciate any help on this issue.
Below is the full code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int ** array;
int rows, cols;
} Smaller;
void printArray (Smaller * s);
int main () {
int x, i, j;
Smaller * sand;
// allocate mem for number of rows
sand->array = malloc (3 * sizeof(int *));
//allocate mem for number of columns
sand->array = malloc(4 * sizeof(int));
sand->array = malloc(4 * sizeof(int));
sand->array = malloc(4 * sizeof(int));
// adding a constant value to the 2D array
for (i = 0; i < 3; i ++) {
for (j = 0; j < 4; j ++) {
sand->array[i][j] = 6;
}
}
printArray(sand);
return 0;
}
void printArray (Smaller * sand) {
printf("Welcome to the printArray function! \n");
int i, j;
for (i = 0; i < 3; i ++)
for(j = 0; j < 4; j ++)
printf("array[%d][%d] = %d \n", i, j, sand->array[i][j]);
}
The problem is, as #tromgy pointed out, you are overwriting the base sand->array with the column arrays instead of assigning them to it. A correct code would look like this:
#include <stdlib.h>
#define NUM_ROWS 3
#define NUM_COLS 4
typedef struct {
int ** array;
int rows;
int cols;
} Smaller;
void print_array(Smaller * s);
int main(void) {
Smaller * sand = malloc(sizeof(Smaller));
if (!sand) return -1; /* allocation failed, abort */
sand->rows = NUM_ROWS;
sand->array = malloc(sizeof(int*[NUM_ROWS]));
if (!sand->array) { /* allocation failed, abort */
free(sand); /* free sand first, though */
return -1;
}
for (size_t i = 0; i < NUM_ROWS; ++i) {
sand->array[i] = malloc(sizeof(int[NUM_COLS]));
if (!sand->array[i]) {
/* free the previous rows */
for (size_t j = 0; j < i; ++j) free(sand->array[j]);
free(sand->array);
free(sand);
return -1;
}
}
/* add a constant value to the array */
for (size_t i = 0; i < NUM_ROWS; ++i) {
for (size_t j = 0; j < NUM_COLS; j ++) {
sand->array[i][j] = 6;
}
}
print_array(sand);
/* Ok, now free everything */
for (size_t i = 0; i < NUM_COLS; ++i) {
free(sand->array[i]);
}
free(sand->array);
free(sand);
/* NOW we may exit */
return 0;
}
As you can see, allocating a structure like this is a lot of work, and you have to free whatever you allocate, so it's probably better to extract it out to a function, something like Smaller * smaller_init(size_t nrows, size_t ncols) and void smaller_destroy(Smaller * s) encapsulating all that work.
I will left an example below so you can compare it to the way you wrote it originally...
About your code:
Declare loop variables inside the for command
May be Smaller do not need to be a pointer
Keep dimensions as variables. It is more flexible
You did not set the values for rows and cols in the struct. And in main() do not use fixed values as 3 and 4 as you did
You should set all cells to different values, not the same. You will feel safer when you see reversible values, like 100*row + column in the example... This way you can see if the loops are ok and all elements are being printed. See this output for printArray():
0 1 2 3
100 101 102 103
200 201 202 203
Each line starts with the line number so you can test it a few times before going on.
make your program test itself. In printArray() for example show the dimensions like this:
printArray[3,4]
0 1 2 3
100 101 102 103
200 201 202 203
See the output of the example
always write the code to free the memory, in the reserve order of the allocation, maybe in a separate function that returns NULL in order to invalidate the pointer back in the calling code, like this
Smaller* freeArray(Smaller* A)
{
printf("\nfreeArray()\n");
for (int i = 0; i < A->rows; i++)
{
free(A->array[i]); // delete lines
printf("row %d free()\n", i);
}
free(A->array); // delete cols
printf("pointer to rows free()\n");
free(A); // delete struct
printf("struct free()\n");
return NULL;
}
This way you know that the pointer sand will not be left pointing to an area that has been free()d. Using such a pointer will crash your program so it may be good to write
sand = freeArray(sand);
output of the example code
printArray[3,4]
0 1 2 3
100 101 102 103
200 201 202 203
freeArray()
row 0 free()
row 1 free()
row 2 free()
pointer to rows free()
struct free()
Example code
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int** array;
int rows, cols;
} Smaller;
void fillArray(Smaller*);
Smaller* freeArray(Smaller*);
Smaller* makeArray(size_t, size_t);
void printArray(Smaller*);
int main(void)
{
int y = 3;
int x = 4;
// sand points to a Smaller
Smaller* sand = makeArray(y, x);
// adding known unique values to cells is easier
fillArray(sand);
printArray(sand); // show values
sand = freeArray(sand); // delete all
return 0;
}
void fillArray(Smaller* A)
{
for (int i = 0; i < A->rows; i++)
for (int j = 0; j < A->cols; j++)
A->array[i][j] = 100 * i + j;
}
Smaller* freeArray(Smaller* A)
{
printf("\nfreeArray()\n");
for (int i = 0; i < A->rows; i++)
{
free(A->array[i]); // delete lines
printf("row %d free()\n", i);
}
free(A->array); // delete cols
printf("pointer to rows free()\n");
free(A); // delete struct
printf("struct free()\n");
return NULL;
}
Smaller* makeArray(size_t y, size_t x)
{
// sand points to a Smaller
Smaller* sand = (Smaller*)malloc(sizeof(Smaller));
sand->rows = y;
sand->cols = x;
// allocate mem for number of rows, that is 'y'
sand->array = malloc(y * sizeof(int*));
// allocate mem for each of the 'x' columns
for (size_t i = 0; i < y; i++)
sand->array[i] = malloc(x * sizeof(int));
return sand;
};
void printArray(Smaller* sand)
{
printf("printArray[%d,%d]\n\n", sand->rows, sand->cols);
for (int i = 0; i < sand->rows; i++)
{
for (int j = 0; j < sand->cols; j++)
printf("%3d ", sand->array[i][j]);
printf("\n");
}
}
About the code
Please SO people do not bother pointing me not to cast the result of malloc(). It is by decision. This common recommendation is a reminiscence of the C-faq of the 90's and now we know that implicit conversions maybe not so good. In fact implicit things may cost you a lot of time: if you malloc() a series of different structs in a program and omit the types if some of them are for example reversed keep in mind that the use of all casts would help you avoid this costly type of mistake...

Get pointer to column of 2D array in C

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.

extend matrix in C

I have a matrix in C and I want to create another one which has double rows than the first matrix.Those added rows I want to have the values of first matrix ,but with changed sign. I am trying to understand dynamic allocation,and I don't understand where I am wrong. The error that compiler says is that:"invalid conversion from void* to int*" . Here is my code:
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
int *extend_matrix=NULL;
int *matrix=NULL;
int *negative_matrix=NULL;
int main(void)
{
int i,j,m,n;
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
int *matrix = (int *)malloc(m * n * sizeof(int));
int *negative_matrix=(int*)malloc(m*n*sizeof(int));
printf("Enter the elements of first matrix\n");
for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
scanf("%d", &matrix[i][j]);
for(i = 0 ; i < m ; i++)
for(j = 0 ; j < n ; j++)
printf("the matrix is: \n",matrix[i][j]);
negative_matrix=-matrix[i][j];
for(i=0;i<m+m;i++)
extend_matrix[i]=realloc(matrix[i],sizeof(int)*(m+m));
for(j=0;j<n;j++)
extend_matrix[j]=realloc(matrix[j],sizeof(int)*n);
extend_matrix[i][j]=matrix[i][j]+negative_matrix[i][j];//how to concatenate them?
getch();
return 0;
}
Seems you're a little confused. Let me to write a short example code
EDIT:
Ok, go here
There you'll find my example. I've not completed it, but just gave an input on how to finish it.
Note this, too:
From 66 to 68 line we have this code:
for (i = 0; i < rows; i++){
free(first_matrix[i]);
}
This is because each elements of our matrix is a pointer and all them point to an array allocated on the heap. So, if you just freed first_matrix, like this:
free(first_matrix);
you would have freed only first_matrix from its own content on the heap (and not that one of each its element)

changing rows into column and column into rows of that 2d array

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

matrix using pointers

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.

Resources