Reputation: 1
For my personal entertainment I am learning C. I am trying to write a matrix calculation header. I have a function to show the matrix, rmat_show(rmatrix *r), which should printf the entire matrix. However, it seems that my data type rmatrix is not passed well to this function.
rmat.h:
// Matrix struct, m x n matrix. Pointer *value points to the contents.
struct srmatrix {
int m,n;
float *value;
};
typedef struct srmatrix rmatrix;
// Show the matrix
void rmat_show(rmatrix* r) {
int i, j;
printf("\nshow\n");
printf("[%dx%d]\n",r->m,r->n);
for (i = 0; i < r->m; i++) {
for (j = 0; j < r->m; j++) {
printf("%d\t",value[(j-1)*r->m+i-1]);
}
printf("\n");
}
}
And I have this as main file:
#include "rmat.h"
int main(int argc, char **argv){
float val[] = {0.1};
rmatrix *r = malloc(sizeof(rmatrix));
r->n = 1;
r->m = 1;
r->value = val;
rmat_show(r);
return 0;
}
After rmat_show I attempt to kill te matrix with another function. It yields the same error, which is: 'incompatible type for argument 1 of 'rmat_show' expected 'rmatrix' but argument was of type 'struct rmatrix *''. I have tried searching 'pointer to typedef' and similar terms, without result. I believe the typedef declaration is not carried over to the function defenition. I use msys and mingw on windows 7.
Thanks for the help.
Edit: added the typedef line I miscopied.
Upvotes: 0
Views: 878
Reputation: 70883
This
struct srmatrix {
int m,n;
float *value;
};
...
void rmat_show(rmatrix* r)
{
...
for (i = 0; i < r->m; i++)
{
for (i = 0; i < r->m; i++)
{
printf("%d\t", value[(n-1)*r->m+m-1]);
}
printf("\n");
}
...
should be this
rmat.h:
#ifndef RMAT_H
#define RMAT_H
typedef struct rmatrix_s {
size_t m, n; /* There is no need to define dimension as signed. */
float * value;
} rmatrix_t;
void rmat_show(rmatrix_t * r);
#endif
rmat.c:
...
#include "rmat.h"
void rmat_show(rmatrix_t * r)
{
...
for (size_t j = 0; j < r->n; j++)
{
for (size_t i = 0; i < r->m; i++)
{
printf("%d\t", value[j*r->m + i]);
}
printf("\n");
}
The main would then have:
...
#include "rmat.h"
int main(int argc, char **argv)
{
...
rmatrix_t * r = malloc(sizeof(*r));
...
To compile this do:
gcc -g -Wall -Wextra -o main main.c rmat.c
Upvotes: 0
Reputation: 36082
Seems you are using the same loop variable twice
for (i = 0; i < r->m; i++) {
for (i = 0; i < r->m; i++)
you probably meant
for (i = 0; i < r->m; i++) {
for (j = 0; j < r->n; j++)
EDIT:
you may want to use the right name of the struct as well
not
rmatrix *r = malloc(sizeof(rmatrix));
but
struct srmatrix *r = malloc(sizeof(struct srmatrix));
whether you include struct or not depends on your compiler version C/C++
Upvotes: 1