This code build dinemically allocated square matrix (designed for the dimenssion of the 1D array), and copy into it an array. The empty places in the matrix are filled with -1.
The thing is I have the pointer to the matrix, but I cannot figure out how to asign vec1's values to it.
Code:
#include<stdio.h>
#include<malloc.h>
#include<math.h>
#include<stdlib.h>
#define LENGTH 11
void CreateMatrix(int vec1[], int ***mat, int *size)
{
int i=0, j, k=0, count=0, temp;
while (vec1[i]>0)
{
count++;
i++;
}
temp=count;
while (sqrt(count)-4!=0)
count++;
*size =count/4;
*mat=(int **)malloc (sizeof(int) * (*size));
if (!mat) exit(0);
for (i=0;i<*size;i++)
(*mat)[i]=(int *)malloc (sizeof(int) * (*size));
if (!mat[i]) exit(0);
while (k<temp)
for (i=0;i<*size;i++)
for (j=0;j<*size;j++)
{
(*mat)[i][j]= vec1[k]; //the problem is
//about this stage
k++;
}
while (k<(*size)*(*size))
for (i=0;i<*size;i++)
for (j=0;j<*size;j++)
{
*mat[i][j]=-1;
k++;
}
}
int main (void)
{
int vec1[LENGTH]={6,4,9,8,9,1,14,56,64,78,-1};
int **mat, size=0;
CreateMatrix(vec1, &mat, &size);
return 1;
}