Segmentation fault in nested for loop with dynamic memory allocation - c

I was preparing a code for simulating Distance Vector Routing using C, however, I faced Segmentation Fault while running.
The code:-
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
/* Date : 03/06/2018
*
* Algorithm
*
* 1. get number of nodes from user
* 2. dynamic alloc new matrix nxn
* 3. create distance vector matrix, if dist > 1000 consider inf
* _| A B C D E F
* A| 0 5 2 3 i i
* B| 5 0 4 5
* C|
* D|
* E|
* F|
* ---------------
*
* 4. create new routing matrix of nxn
* 5. create new minimizing array for the node
* 6. find minimum of the array, allocate new value
*
* copyleft
*/
#define inf 1000
int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);
int main(){
int n; //No of nodes
int i,j; //Counters
printf("> enter the number of nodes in the network... ");
scanf("%d",&n);
int **DisMat = (int **)malloc(n * n * sizeof(int)); //Dynamic allocation of Distance Matrix
for(i=0; i<n; i++){ // x directional loop
printf("> distance vector table for node %c\n",i+65);
for(j=0; j<n; j++){ // y directional loop
printf("> distance from %c... ",j+65);
if(j==i) { DisMat[i][j] = 0; printf("0");}
else scanf("%d",&DisMat[i][j]);
}// y directional loop
}// x directional loop
int **NewDisMat = (int **)malloc(n * n * sizeof(int)); //New Distance Matrix
char **Hop = (char **)malloc(n * n * sizeof(char)); //New Hop Matrix
for(i=0; i<n; i++){
for(j=0; j<n; j++){
Hop[i][j] = '-'; //All Hops Nullified
}
}
dvr(DisMat, NewDisMat, Hop, n); //Distance Vector Routing
return 0;
}//main
void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){ //DVR function
int x=0, y=0, z=0, conCount;
int hopPoint;
int *mini = (int *)malloc((l-1) * sizeof(int));
int *mzer = (int *)malloc((l-1) * sizeof(int));
for(x=0; x<l; x++){ // x directional propagation
mini[0] = x;
z = 1; conCount=0;
do{
if((dvt[x][y] < inf) && (y != x)) {
mini[z] = y;
z++;
conCount++;
}
y++;
}while(y<l);
y = 0; z = 0;
for(y = 0; y<l; y++){
while(z<conCount){
mzer[z] = dvt[mini[z]][y];
z++;
}
newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
hopper[x][y] = hopPoint + 65;
}// y directional propagation
}// x directional propagation
}//dvr
int min_r(int arr[], int *index, int len){
//Sequential minimum search
int min;
int ind = 0;
min = arr[ind];
for(ind = 0; ind<len; ind++){
if(arr[ind] < min){
min = arr[ind];
*index = ind;
}
}
return min;
}//min_r
void dvtDisp(int *dvt[], int size){
int x, y;
printf("_ |");
for(x = 0; x<size; x++){
printf("\t%c",65 + x);
}
printf("\n");
for(y = 0; y<size; y++){
printf("%c |",y + 65);
for(x = 0; x < size; x++)
printf("\t%d",dvt[x][y]);
}
}
void dvtDispNew(int *dvt[], char *hopto[], int size){
int x, y;
printf("_ |");
for(x = 0; x<size; x++){
printf("\t%c\thop",65 + x);
}
printf("\n");
for(y = 0; y<size; y++){
printf("%c |",y + 65);
for(x = 0; x < size; x++)
printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
}
}
I got the following output on the terminal during execution.
anwesh#bionic-Inspiron:~/Documents/NS2/LAB/prog5$ gcc main.c
anwesh#bionic-Inspiron:~/Documents/NS2/LAB/prog5$ ./a.out
> enter the number of nodes in the network... 5
> distance vector table for node A
Segmentation fault (core dumped)
I tried to run it on gdb but could not figure out what the results meant. Here the gdb output:-
Starting program: /home/anwesh/Documents/NS2/LAB/prog5/a.out
> enter the number of nodes in the network... 5
> distance vector table for node A
Program received signal SIGSEGV, Segmentation fault.
0x000055555555487e in main ()
(gdb)
Initially I thought it'd be a problem related to dynamic memory allocation, but I do not know the exact cause. I've checked the code multiple times to see if there are any naive mistakes, but I couldn't.
Please help me out here! Thanks in advance.

The line
int **DisMat = (int **)malloc(n * n * sizeof(int)); //Dynamic allocation of Distance Matrix
is not valid. DisMat is an array of pointers to an array of ints. So we need to allocate n pointers to ints first:
int **DisMat = malloc(n * sizeof(int*));
Then we need to n-times allocate array of n ints:
for(size_t i = 0; i < n; ++i) {
DisMat[i] = malloc(n * sizeof(int));
}
The same goes for Hop and NewDisMat.
Remember, that malloc does not check for multiplication overflow.
The following code runs fine:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
/* Date : 03/06/2018
*
* Algorithm
*
* 1. get number of nodes from user
* 2. dynamic alloc new matrix nxn
* 3. create distance vector matrix, if dist > 1000 consider inf
* _| A B C D E F
* A| 0 5 2 3 i i
* B| 5 0 4 5
* C|
* D|
* E|
* F|
* ---------------
*
* 4. create new routing matrix of nxn
* 5. create new minimizing array for the node
* 6. find minimum of the array, allocate new value
*
* copyleft
*/
#define inf 1000
int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);
int main(){
int n; //No of nodes
int i,j; //Counters
printf("> enter the number of nodes in the network... ");
scanf("%d",&n);
int **DisMat = malloc(n * sizeof(*DisMat)); //Dynamic allocation of Distance Matrix
assert(DisMat != NULL);
for(size_t i = 0; i < n; ++i) {
DisMat[i] = malloc(n * sizeof(*DisMat[i]));
assert(DisMat[i] != NULL);
}
for(i=0; i<n; i++){ // x directional loop
printf("> distance vector table for node %c\n",i+65);
for(j=0; j<n; j++){ // y directional loop
printf("> distance from %c... ",j+65);
if(j==i) { DisMat[i][j] = 0; printf("0");}
else scanf("%d",&DisMat[i][j]);
printf("\n");
}// y directional loop
}// x directional loop
int **NewDisMat = malloc(n * sizeof(*NewDisMat)); //New Distance Matrix
assert(NewDisMat != NULL);
for(size_t i = 0; i < n; ++i) {
NewDisMat[i] = malloc(n * sizeof(*NewDisMat[i]));
assert(NewDisMat[i] != NULL);
}
char **Hop = malloc(n * sizeof(*Hop)); //New Hop Matrix
assert(Hop);
for(size_t i = 0; i < n; ++i) {
Hop[i] = malloc(n * sizeof(*Hop[i]));
assert(Hop[i] != NULL);
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
Hop[i][j] = '-'; //All Hops Nullified
}
}
dvr(DisMat, NewDisMat, Hop, n); //Distance Vector Routing
for(size_t i = 0; i < n; ++i) {
free(DisMat[i]);
}
free(DisMat);
for(size_t i = 0; i < n; ++i) {
free(NewDisMat[i]);
}
free(NewDisMat);
for(size_t i = 0; i < n; ++i) {
free(Hop[i]);
}
free(Hop);
return 0;
}//main
void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){ //DVR function
int x=0, y=0, z=0, conCount;
int hopPoint;
int *mini = (int *)malloc((l-1) * sizeof(int));
int *mzer = (int *)malloc((l-1) * sizeof(int));
for(x=0; x<l; x++){ // x directional propagation
mini[0] = x;
z = 1; conCount=0;
do{
if((dvt[x][y] < inf) && (y != x)) {
mini[z] = y;
z++;
conCount++;
}
y++;
}while(y<l);
y = 0; z = 0;
for(y = 0; y<l; y++){
while(z<conCount){
mzer[z] = dvt[mini[z]][y];
z++;
}
newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
hopper[x][y] = hopPoint + 65;
}// y directional propagation
}// x directional propagation
}//dvr
int min_r(int arr[], int *index, int len){
//Sequential minimum search
int min;
int ind = 0;
min = arr[ind];
for(ind = 0; ind<len; ind++){
if(arr[ind] < min){
min = arr[ind];
*index = ind;
}
}
return min;
}//min_r
void dvtDisp(int *dvt[], int size){
int x, y;
printf("_ |");
for(x = 0; x<size; x++){
printf("\t%c",65 + x);
}
printf("\n");
for(y = 0; y<size; y++){
printf("%c |",y + 65);
for(x = 0; x < size; x++)
printf("\t%d",dvt[x][y]);
}
}
void dvtDispNew(int *dvt[], char *hopto[], int size){
int x, y;
printf("_ |");
for(x = 0; x<size; x++){
printf("\t%c\thop",65 + x);
}
printf("\n");
for(y = 0; y<size; y++){
printf("%c |",y + 65);
for(x = 0; x < size; x++)
printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
}
}
Side note: Remember that sizeof(int*) == sizeof(*DisMat), so I prefer:
int **DisMat = malloc(n * sizeof(*DisMat));
By using that expression type *variable = malloc(n * sizeof(*variable)) I can remember, that I am allocating the correct type, an array of pointers to ints in case of DisMat, cause typeof(*DisMat) == int*, and make less errors.

Related

C Programming: doing matrix multiplication of two contiguous, row-major arrays

I'm trying to write a function that does naive matrix multiplication of two contiguous, row-major arrays. But when I attempt to print each value at the end I get garbage. I'm guessing it's because I've mixed up the proper iterations and scaling needed to jump rows/columns. Does anyone have any advice?
Full code necessary is below:
#include <stdio.h>
#include <stdlib.h>
void dmatmul(double *a, double *b, double *c, int astride, int bstride, int cdim_0, int cdim_1) {
int i, j, p;
for (i = 0; i < cdim_0; i++) {
for (j = 0; j < cdim_1; j++) {
c[i * cdim_1 + j] = 0.0;
for (p = 0; p < (astride); p++) {
c[i * cdim_1 + j] += a[i * (astride) + p] * b[p * (bstride) + j];
}
}
}
}
int main(void) {
double *x, *y, *z;
int xdim_0, xdim_1, ydim_0, ydim_1, zdim_0, zdim_1, i, j;
xdim_0 = 2;
xdim_1 = 4;
ydim_0 = 4;
ydim_1 = 2;
zdim_0 = 2;
zdim_1 = 2;
x = (double *) malloc (xdim_0 * xdim_1 * sizeof(double));
y = (double *) malloc (ydim_0 * ydim_1 * sizeof(double));
z = (double *) malloc (zdim_0 * zdim_1 * sizeof(double));
for (i = 0; i < xdim_0 * xdim_1; i++) {
x[i] = i + 1;
y[i] = 2 * (i + 1);
}
dmatmul(x, y, z, xdim_1, ydim_1, zdim_0, zdim_1);
printf("\nMatrix product of X and Y dimensions: (%d, %d)\n", zdim_0, zdim_1);
printf("Matrix product of X and Y values:");
for (i = 0; i < zdim_0; i++) {
printf("\n");
for (j = 0; j < zdim_1; i++) {
printf("\t%f", z[i * zdim_1 + j]);
}
}
return 0;
}
The primary problem is a typo in the inner for loop doing the printing. You have:
for (j = 0; j < zdim_1; i++)
but you ned to increment j, not i:
for (j = 0; j < zdim_1; j++)
Here's my code, which has an independent matrix printing function appropriate for the arrays you're using:
/* SO 7516-7451 */
#include <stdio.h>
#include <stdlib.h>
static void dmatmul(double *a, double *b, double *c, int astride, int bstride, int cdim_0, int cdim_1)
{
int i, j, p;
for (i = 0; i < cdim_0; i++)
{
for (j = 0; j < cdim_1; j++)
{
c[i * cdim_1 + j] = 0.0;
for (p = 0; p < (astride); p++)
{
c[i * cdim_1 + j] += a[i * (astride) + p] * b[p * (bstride) + j];
}
}
}
}
static void mat_print(const char *tag, int rows, int cols, double *matrix)
{
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4.0f", matrix[i * cols + j]);
putchar('\n');
}
}
int main(void)
{
int xdim_0 = 2;
int xdim_1 = 4;
int ydim_0 = 4;
int ydim_1 = 2;
int zdim_0 = 2;
int zdim_1 = 2;
double *x = (double *)malloc(xdim_0 * xdim_1 * sizeof(double));
double *y = (double *)malloc(ydim_0 * ydim_1 * sizeof(double));
double *z = (double *)malloc(zdim_0 * zdim_1 * sizeof(double));
for (int i = 0; i < xdim_0 * xdim_1; i++)
{
x[i] = i + 1;
y[i] = 2 * (i + 1);
}
mat_print("X", xdim_0, xdim_1, x);
mat_print("Y", ydim_0, ydim_1, y);
dmatmul(x, y, z, xdim_1, ydim_1, zdim_0, zdim_1);
mat_print("Z", zdim_0, zdim_1, z);
printf("\nMatrix product of X and Y dimensions: (%d, %d)\n", zdim_0, zdim_1);
printf("Matrix product of X and Y values:\n");
for (int i = 0; i < zdim_0; i++)
{
for (int j = 0; j < zdim_1; j++)
printf("\t%f", z[i * zdim_1 + j]);
printf("\n");
}
return 0;
}
I've also initialized the variables as I declared them. The code should, but does not, check that the memory was allocated.
When I ran this code without your printing, I got the correct result, so then I took a good look at that and saw the problem.
X (2x4):
1 2 3 4
5 6 7 8
Y (4x2):
2 4
6 8
10 12
14 16
Z (2x2):
100 120
228 280
Matrix product of X and Y dimensions: (2, 2)
Matrix product of X and Y values:
100.000000 120.000000
228.000000 280.000000

How to specify the number of threads I want to use?

I am trying to Multiply the matrix with use of threads. The code seems to be working. I just need to know how to specify the number of threads so that I can count how much time it's taking. I want to create a table of threads and time it's taking to compute the matrix.
I am dynamically allocating the matrix and filling it with random numbers.
I am creating threads to compute the resultant matrix.
C Program to multiply two matrix using pthreads without use of global variables
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
//Each thread computes single element in the resultant matrix
void *mult(void* arg)
{
int *data = (int *)arg;
int k = 0, i = 0;
int x = data[0];
for (i = 1; i <= x; i++)
k += data[i]*data[i+x];
int *p = (int*)malloc(sizeof(int));
*p = k;
//Used to terminate a thread and the return value is passed as a pointer
pthread_exit(p);
}
//Driver code
int main()
{
int i, j, k, row1, col1, row2, col2, r, sum;
printf("Enter the number of rows for matrix 1\n");
scanf("%d",&row1);
printf("Enter the number of columns for matrix 1 \n");
scanf("%d",&col1);
printf("Enter the number of rows for matrix 2 \n");
scanf("%d",&row2);
printf("Enter the number of columns for matrix 2\n");
scanf("%d",&col2);
int **a = (int **) malloc(row1 * sizeof(int *));
for(i=0;i<row1;i++)
a[i] = (int *) malloc(col1 * sizeof(int));
int **b = (int **) malloc(row2 * sizeof(int *));
for(i=0;i<row2;i++)
b[i] = (int *) malloc(col2 * sizeof(int));
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
a[i][j] = (rand()%9) + 1;
}
}
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
b[i][j] = (rand()%9) +1;
}
}
int N = row1*col2;
//declaring array of threads of size row1*col2
pthread_t *threads;
threads = (pthread_t*)malloc(N*sizeof(pthread_t));
int count = 0;
int* data = NULL;
for (i = 0; i < row1; i++)
for (j = 0; j < col2; j++)
{
//storing row and column elements in data
data = (int *)malloc((N)*sizeof(int));
data[0] = col1;
for (k = 0; k < col1; k++)
data[k+1] = a[i][k];
for (k = 0; k < row2; k++)
data[k+col1+1] = b[k][j];
//creating threads
pthread_create(&threads[count++], NULL,
mult, (void*)(data));
}
printf("RESULTANT MATRIX IS :- \n");
for (i = 0; i < N; i++)
{
void *k;
//Joining all threads and collecting return value
pthread_join(threads[i], &k);
int *p = (int *)k;
printf("%d ",*p);
if ((i + 1) % col2 == 0)
printf("\n");
}
return 0;
}

While passing 2d matrix using double pointer to print function it printing last element of matrix zero

Here is simple code just reading two matrix one is 3*3 dimensional and other is 3*1 dimensional. while printing first matrix A[3][3] the last element of matrix is printing zero in void printarray(double **A, int n ) function.
Below my code:
#include <stdio.h>
#include<malloc.h>
void printarray(double **A, int n );
void main(){
double **A;
int n = 3;
int row,col;
double *b;
A = (double **) malloc(n * sizeof(double**));
for (row = 1; row<= n; row++) {
A[row] = (double *) malloc(n * sizeof(double));
}
// Initialize each element.
for (row = 1; row<= n; row++) {
for (col = 1; col<= n; col++) {
printf("A[%d][%d]= %u \t",row,col,&A[row][col]);
scanf("%lf",&A[row][col]); // or whatever value you want
}
}
//print A
printf("\n...........array in main.................\n");
for (row = 1; row<= n; row++) {
for (col = 1; col<= n; col++) {
printf("A[%d][%d]=%u \t %lf",row,col,&A[row][col],A[row][col]);
printf("\n");
}
}
b = (double *) malloc(n * sizeof(double));
printf("\n enter the elemet of b \n"); // Initialize each element.
for (row = 1; row<= n; row++){
printf("address=%u \t",&b[row]);
printf("b[%d]=",row);
scanf("%lf",&b[row]);
printf("\n");
}
printarray((double **)A, n );
}// Print it
void printarray(double **A, int n ){
int i;
int j;
printf("\n.....print a.............\n");
for( j = 1; j <= n; j++ ){
for( i = 1; i <= n; i ++){
printf("A[%d][%d]= %u \t",j,i,&A[j][i]);
printf( "%lf ", A[j][i] );
}
printf( "\n" );
}
}
One the problem comes from the indexing of your array. Array indexing start at 0.
This means that in order to loop through your array, you need your for loop to start at 0 up to n-1:
for (int row=0; row<n;++row) {/*...*/}

c - warning: pointer argument of a function may be used uninitialized

#include <stdio.h>
#include <stdlib.h>
void multiplyMatrix (int **first, int **second, int **multiply);
int m, n, p, q, i, c, d, k, sum = 0;
int main()
{
int **first, **second, **multiply;
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
first = (int **) malloc(m * sizeof(int *));
for(i = 0 ; i < n ; i++){
first[i]=(int *)malloc(m * sizeof(int *));
}
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
second = (int **) malloc(p * sizeof(int *));
for(i = 0 ; i < q ; i++){
second[i]=(int *) malloc(p * sizeof(int *));
}
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
/*for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}*/
multiplyMatrix(first, second, multiply);
printf("Product of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
void multiplyMatrix (int **first, int **second, int **multiply)
{
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
}
The program i want to write should be like this: The program asks to the user to enter both the sizes and elements of 2 matrices (or you can call it 2d arrays). Then it will multiply those matrices and print the answer.
The problem i am getting: i used pointers and malloc functions to dynamically allocate the matrices. for the multiplication, i created a function called "multiplyMatrix" which i get a warning for one of the arguments of it in the decleration. here is the warning:
warning: 'multiply' may be used uninitialized in this function.
so there is some kind of a problem with initializing this argument. i feel like the answer is simple but at the same time i can't find the solution.
You have not allocated the memory to be used by the multiply matrix - hence it is being flagged as uninitialised.
You also need to review how you use your row and column values when allocating the first and second matrices, for example:
first = (int **) malloc(m * sizeof(int *));
for(i = 0 ; i < m ; i++){
first[i]=(int *)malloc(n * sizeof(int *));
}
(Incorporates comment made by wildplasser)
This will allow first to be accessed as first[row][col]
the variable multiply was declared in main(), however it is never set to point to anything. it needs to be created the same way as first and second, however it does not need to have its' values filled in.
Suggestions to improve your code:
Create a function to allocate memory for a matrix.
Create a function to read matrix data.
Create a function to deallocate memory of a matrix.
Avoid use of global variables. Pass the necessary arguments to a function.
Use those functions instead of duplicating code in main.
#include <stdio.h>
#include <stdlib.h>
int** createMatrix(int rows, int cols)
{
int i;
int** mat = malloc(sizeof(*mat)*rows);
for ( i = 0; i < rows; ++i )
mat[i] = malloc(sizeof(*mat[i])*cols);
return mat;
}
void readMatrix(int** mat, int rows, int cols)
{
int r;
int c;
for ( r = 0; r < rows; ++r )
for ( c = 0; c < cols; ++c )
scanf("%d", &mat[c][c]);
}
void deleteMatrix(int** mat, int rows)
{
int i;
for ( i = 0; i < rows; ++i )
free(mat[i]);
free(mat);
}
void multiplyMatrix (int **first, int **second, int **multiply,
int frows, int fcols, int scols)
{
int sum = 0;
int r;
int c;
int k;
for (r = 0; r < frows; r++) {
for (c = 0; c < scols; c++) {
sum = 0;
for (k = 0; k < fcols; k++) {
sum += first[r][k]*second[k][c];
}
multiply[r][c] = sum;
}
}
}
int main()
{
int m, n, p, q;
int r, c;
int **first, **second, **multiply;
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
first = createMatrix(m, n);
printf("Enter the elements of first matrix\n");
readMatrix(first, m, n);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
second = createMatrix(p, q);
printf("Enter the elements of second matrix\n");
readMatrix(second, p, q);
multiply = createMatrix(m, q);
multiplyMatrix(first, second, multiply, m, n, q);
printf("Product of entered matrices:-\n");
for (r = 0; r < m; r++) {
for (c = 0; c < q; c++)
printf("%d\t", multiply[r][c]);
printf("\n");
}
deleteMatrix(multiply, m);
deleteMatrix(second, p);
}
deleteMatrix(first, m);
return 0;
}

Transpose a matrix via pointer in C

I'm trying to transpose a matrix in C while passing the matrix to a function and return a pointer to a transposed matrix. What am I doing wrong in the second while loop?
in main
ptr = (float *) getMatrix(numRowsB, numColsB);
transposePtr = transpose(ptr, numRowsB, numColsB);
printf("\nBtranspose =\n");
printMatrix(transposePtr, numColsB, numRowsB);
create matrix
float* getMatrix(int n, int m)
{
int i, j;
float *arrayPtr;
if ((n <= 0) || (m <= 0))
{
printf("function getMatrix(): matrix dimensions are invalid\n");
return NULL;
}
arrayPtr = (float *) malloc(n*m*sizeof(float));
if(arrayPtr == NULL)
{
printf("function getMatrix: Unable to malloc array\n");
return NULL;
}
transpose function
float* transpose(float *matrix, int n, int m)
{
int i = 0;
int j = 0;
float num;
float *transposed=(int*) malloc(sizeof(int)*n*m);
while(i < n-1)
{
while(j < m-1)
{
num = *(matrix+i*m+j);
*(transposed+j*m+i)= num;
j++;
}
i++;
}
return transposed;
}
print fucntion
void print(float *matrix, int n, int m)
{
int i = 0;//row counter
int j = 0;//col counter
for(i = 0; i < n; i++){
printf("\n");
for(j = 0; j < m; j++){
printf("%f ", *(matrix + i*n + j));
}
}
}
Example input:
1 2 3
4 5 6
Output:
1.000000 0.000000
2.000000 3396.580087
-0.000000 0.000000
Part of the problem was your print function
Here is a version of your functions that works:
float* transpose(float *matrix, int n, int m)
{
int i = 0;
int j = 0;
float num;
float *transposed=malloc(sizeof(float)*n*m);
while(i < n) {
j = 0;
while(j < m) {
num = *(matrix + i*m + j);
*(transposed + i+n*j) = num; // I changed how you index the transpose
j++;
}
i++;
}
return transposed;
}
void print(float *matrix, int n, int m)
{
int i = 0;//row counter
int j = 0;//col counter
for(i = 0; i < n; i++){
printf("\n");
for(j = 0; j < m; j++){
printf("%f ", *(matrix + i*m + j)); // Changed from n to m
}
}
}
There were a few things.
Use sizeof(float) instead of sizeof(int)
Your loop should be i < n and j < m instead of i < n-1 and j < m-1 and finally you need to reset j to zero every time
The matrix indexes in inner most loop of your transpose function was incorrect
Your print function was using the wrong variable in the multiplication
Also it is generally considered bad practice to cast the result of malloc in C.

Resources