Hi, this is my first topic in this site. So I'm going to go directly to the problem with reallocating two dimensional array with realloc, because I want to expand the 2D array without lousing previous data.
So I came with idea.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <stdio.h>
#include <stdlib.h>
int **asd;
int size = 10;
int main(void)
{
int i,j;
asd = (int **)realloc(asd, sizeof(int)*(size*size));
for(i = 0 ; i < size ; i++)
asd[i] = (int *)realloc(asd[i], sizeof(int)*size);
for(i = 0 ; i < size ; i++)
for(j = 0 ; j < size ; j++)
asd[i][j] = 10;
for(i = 0 ; i < size ; i++){
for(j = 0 ; j < size ; j++){
printf(" %d ", asd[i][j]);
}
putchar('\n');
}
return 0;
}
|
But after few failure attempts I realized, that maybe I'm destroying the other pointers after the first cycle of reallocating the first pointer.
Next I to do try something else to see if it works, and it did work. I replace the realloc with malloc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <stdio.h>
#include <stdlib.h>
int **asd;
int size = 10;
int main(void)
{
int i,j;
asd = (int **)realloc(asd, sizeof(int)*(size*size));
for(i = 0 ; i < size ; i++)
asd[i] = (int *)malloc(sizeof(int)*size);
for(i = 0 ; i < size ; i++)
for(j = 0 ; j < size ; j++){
asd[i][j] = 10;
}
for(i = 0 ; i < size ; i++){
for(j = 0 ; j < size ; j++){
printf(" %d ", asd[i][j]);
}
putchar('\n');
}
return 0;
}
|
I still didn't try to see if data stay whole after using malloc, but i dont belive it will.
Maybe I'm going into the wrong direction, so I need help.
Now I'm going to explain the whole idea why I need this. The thing is, that I'm learning how draw graphic primitives, and most of the code, wich involves mathematics, I'm trying to write by myself.
And I'm using one 2D matrix for all objects to tell the program wich objects are related. I did that and now I want to optimize the code by changing the 2D matrix size when object is added or removed. The 2D matrix will be used to save the current graphics in a file.
And I have another question, when reallocate memory, must I have even set of bytes when divided by four to equals zero.
For my last question I'm not shure if I ask correctly.