I am trying to define a matrix like so
I have a structure
typedef struct _struct {
int name;
int data;
} myDataType;
Afterwards i am defining a matrix
int **myMatrix = calloc(size,sizeof(int*));
for()
// allocate rows except last index
myMatrix[last_index_in_matrix] = calloc(1,sizeof(myDataType));
The problem is that I cannot access myMatrix[last_index].data it says, also tried with -> (i really don’t know when to use what)
request for member ‘data’ in something not a structure or union
What am i doing wrong ? Should i post actual code ? If this method is not possible can i get a different suggestion ?
UPDATE: I’ll say it again, the matrix is all int, i just want the last row to point to that structure, some of the comments have not taken this into consideration. That is way i declared it the way i did in my example.
Let’s start simple:
You want to create a matrix of
myDataType. If you know the number of rows and columns at compile time, you can simply declare it asIf you need to allocate it dynamically, you would do something like this:
Either way, to access the struct members at the
i‘th andj‘th elements, you’d write:Edit
Ah, now I get it.
Don’t do that.
There’s no guarantee that pointers to
structtypes have the same size and representation as pointers toint. They do on most common architectures, but it’s not something you can rely on. If they don’t, then you’re going to have runtime problems.From a design point of view this just makes me itchy; if you need to associate that struct with a matrix, create a new aggregate type to explicitly do so:
This will make life easier when you need to free up the matrix as well.
FWIW, to do what you wanted, you’d need to engage in some casting gymnastics such as
and
but as I said above, if the pointer types are not compatible, the conversion could lead to runtime errors. Don’t do it. Bad juju.