Good morning everybody!
I'm working on an application where I have a structure and I'll use its parameters in a bidimensional matrix [n][k], where n is known and k is unknown and might be different for each index of the dimension n. I've fixed a "kick" for k, and I use realloc to increase memory as k increases.
I need to store the value of k in the structure, so I thought about putting the value of each k in the first index of the second dimension:
Code:
array[i][0].n = k_current;
so I know the number of elements in the second dimension for each i, what will help me when I'll read the values of the structure.
My explanation might be confusing, so here is a piece of code I've made to illustrate it better (that's just an example, the matrix will not be filled this way, and I've fixed n=2):
(Type values for each k and -1 to finish).
Code:
typedef struct {
double a;
int b;
} FOO;
int main()
{
int i, j, k;
double x = 0;
FOO **arr;
int n = 2;
int kick = 2;
arr = malloc(n*sizeof(FOO*));
for(i=0; i<n; i++)
{
x = 0;
k = 0;
printf("Type arr[%d][k].a: \n", i);
while(x != -1)
{
if(k == 0) arr[i] = malloc(kick*sizeof(FOO));
printf("k = %d: ", k);
scanf("%lf", &x);
if(x == -1) break; // that's just an example
if(k == kick)
{
kick += 2;
FOO *temp = realloc(arr[i], kick*sizeof(FOO));
if(!temp) exit(1);
arr[i] = temp;
}
arr[i][k++].a = x;
}
arr[i][0].b = k; // Here's my question!
printf("Ok, you've typed %d values of a.\n", arr[i][0].b);
}
printf("\nEND.");
getch();
}
Do you think this is a good way to store the values of k? I'm worried because the parameter b won't be defined for the other indexes of the second dimension. Is that a problem, even if I won't access them? And also, should I initialize the other parameters of the structure in the array?
Thank's in advance!