typedefstruct species
{ int Trophic;
int Niche[10000];
} species;
So each species has a Trophic value and a Niche array. The Niche array can at maximum carry 9999 elements (0 to 9999). But in reality, MOST of the species take JUST 2 or 3 elements in their Niche array. Just 1 or 2 species use a large number of Niche elements. But still I am having to assign a size of 10000 to every species' Niche array. That must be taking a lot of memory.
Now the number of Niche elements that a specie occupies in its niche array (i.e how many elements of the niche array are occupied) is decided as the program runs. But once decided, it remains constant.
So I am trying to use Dynamic Memory Allocation for the Niche array so that the species that take a few Niche elements are assigned a small size to their Niche array and the species that take a larger number of Niche elements get larger size to their Niche array. But I am not able to use a pointer inside structure.
I am very new to pointers etc. But still have studied & practiced a bit of them but not able to use it in structures.
struct Species
{
int trophic;
unsignedint numNiches;
int* niche;
};
int constructSpecies(Species& s, int trophic, unsignedint numNiches){
s.trophic = trophic;
s.numNiches = numNiches;
s.niche = (int*) malloc(numNiches*sizeof(int));
if(s.niche == NULL){
return some error value;
}
return some ok value;
}
void destructSpecies(Species& s){
free (s.niche);
}
I've probably made a mistake somewhere, but that might help. So for example:
1 2 3 4 5 6 7 8 9 10 11 12
Species s;
int ret = constructSpecies(s, 1, 50);
if(ret != OK){ do something. }
for(unsignedint i = 0; i < s.numNiches; i++){
s.niche[i] = some int;
}
//... Do whatever
//Don't forget to destruct!
destructSpecies(s);
Learning from your code, I have developed a short code (using calloc). Can u please check it carefully if I have made any mistakes ,like [COLOR="red"]memory leaks[/COLOR] etc.. (although I have checked it by printing the outputs, but am not shure about [COLOR="red"]memory leaks[/COLOR])
typedefstruct species
{
int * niche;
} species;
void main()
{
constint TotalSpecies = 3;
species s[TotalSpecies];
int i,j,nichesize;
for( i = 0; i < TotalSpecies; i++)
{
printf("enter the niche size of specie %d \n",i);
scanf("%d",&nichesize);
s[i].niche = calloc(nichesize,sizeof(int));
printf("enter the niche value(s) of specie %d\n",i);
for(j=0;j<nichesize;j++)
scanf("%d",&s[i].niche[j]);
}
for( i = 0; i < TotalSpecies;i++)
free(s[i].niche);
}
Looks good to me! In C++ there are a number of programming practices which significantly reduce the likely-hood of memory leaks - I don't really know how you should go about it in C. However from what I can see you are memory leak free :)