Jack
Jack

Reputation: 371

How to use a dynamic matrix in C

I have a data type defined by me, and I want to create a matrix of that data type, but I'm not able to use it.

I have typedef char data[10];

data  **matrix;
matrix=(data**)malloc(n*sizeof(data*));
for (i=0;i<x;++i)
    matrix[i]=(data*)malloc(m*sizeof(data));
matrix[i][j]="example";

But in the last line i get an error saying incompatible types, even if I use data of the same type (in this case from a dynamic vector). Is there an error creating the matrix or using it?

Upvotes: 0

Views: 453

Answers (2)

kotlomoy
kotlomoy

Reputation: 1430

Here

matrix[i][j]="example";

you assign to array which is illegal. Try this:

strcpy( matrix[i][j], "example" );

Please note that strcpy is insecure, use more secure alternative for your system - strlcpy or strcpy_s. Or you can follow H2CO3's suggestion.

Upvotes: 1

Gangadhar
Gangadhar

Reputation: 10516

Assuming estado is char type.

estado  **matrix = malloc(n*sizeof(char*));  //allocte number of pointers 

for (i=0;i<x;++i);       
matrix[i]=malloc(m); //allocate each pointer
matrix[i]="example";

Assuming estado is int type. This is same for struct.

estado  **matrix = malloc(n*sizeof(int*)); //allocte number of pointers 

for (i=0;i<x;++i); 
{      
matrix[i]=malloc(m *sizeof(int)); //allocate each pointer

for(j=0;j<m;j++)  
matrix[i][j]=1;  or You can also use `memcpy()`  
}

Upvotes: 1

Related Questions