Reputation: 11
:D
My problem is I have to divide a bigger array into smaller fixed size arrays. I'm just wondering what is the best method for dividing an array. I saw a question here and derived a method out of it. The number of array is changing. Indices is the array where i'm pointing the pointers.
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y <= num; y++) {
ptr[y] = ptr[y-1] + Size;//points the next pointer to it's position.
}
What I wanted to ask is my method correct? And if there is alternative solutions for dividing arrays. I'm going to pass the small arrays by the way.
Upvotes: 0
Views: 279
Reputation: 203
I usually try to avoid loops where the result of each iteration depends on the previous iteration.
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y < num; y++) {
ptr[y] = ptr[0] + y*Size;//points the next pointer to it's position.
}
The reason for this is that if anyone changes the starting value of y
then the loop is broken. For instance if you decided that ptr[1]
will never be used you could start y
at 2. This would appear to be correct except that ptr[2]
will get assigned to ptr[1]
which never got initialized.
For such a simple loop what you are doing is fine.
You don't mention how you are planning to use these pointers but if it is something like:
for(ii = 0; ii < num; ++ii)
myFunction(ptr[ii]);
Then it may be simpler to just use 'indicies' directly:
for(ii = 0; ii < num; ++ii)
myFunction(indicies + ii*Size);
or this way:
for(ii = 0; ii < num; ++ii)
myFunction(indicies[ii*Size]);
Upvotes: 1
Reputation: 2373
Some minor fixes use smaller than rather than smaller than or equal + you have to calculate size,
int *ptr[num];//array of pointers
ptr[0] = indices;//points the first pointer in the first element of the array
for (y = 1; y < num; y++) {
ptr[y] = ptr[y-1] + Size;//points the next pointer to it's position.
}
Now this method will not actually divide the array, but will create pointers to places inside the array. you cannot delete the new divided sub-arrays individually. You can only delete the bigger array. This solution has better performance than copying the bigger array to smaller sub-arrays.
Upvotes: 0