Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
can I make an array in Cto hold only positive numbers greater than zero? Like the unsigned type of int, but in array.

I have the following code to make that check when I parsing the elements into the array but I think that this check it 1) slow done the processing, 2) is a wrong method to do the check.
C
[EDIT] Added code from comment
int count = 10;  // Can be 0 - 10
int* children = (int*)malloc(count * sizeof(int));

for (i = 0; i < count; ++i) 
{
    children[i] = atoi(lines[i + 1]);
		
    if (children[i] <= 0)
        return(0);
}
Posted
Updated 2-Dec-14 8:17am
v2
Comments
Sergey Alexandrovich Kryukov 2-Dec-14 13:42pm    
Please, what is that beast, "physical number"?
—SA
PIEBALDconsult 2-Dec-14 13:49pm    
I expect he means "counting number".
[no name] 2-Dec-14 14:04pm    
numbers from 0 to ~ (infinite)
Sergey Alexandrovich Kryukov 2-Dec-14 19:51pm    
I would say, their not less chemical than physical... :-)
—SA
George Jonsson 2-Dec-14 13:43pm    
How did you declare your array?
E.g. unsigned int children[n];

1 solution

Checking is always worth it: it saves a heck of a lot of grief later on!

The code isn't bad at all - it could possibly use disposal of the multiple-array-access code, but the compiler will likely optimise that anyway.
You could try
C#
for (i = 0; i < count; ++i) {
    if ((children[i] = atoi(lines[i + 1])) <= 0 )
        return(0);
    }
Which might be slightly more efficient, but less readable.
 
Share this answer
 
Comments
[no name] 2-Dec-14 14:43pm    
ok so we have the if statement first and we the check on time the elements? Hmmmmm what if we have an array of 2.000.000 ? Is worth to change my code or not?
OriginalGriff 2-Dec-14 15:01pm    
For a loop that big, it may be worth some optimisation, but it depends on how likely it is that you will have errors!
If they aren't likely at all, then probably what you have is going to be pretty much optimal, but it's worth doing some timing tests with the release version (so it gets full optimisations) to see if my minor change is worth while - it's worth losing readability to save significant time over a large loop. But not for a loop that runs one in a blue moon and only processes a couple of dozen iterations!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900