仅将物理数字解析为C中的数组 [英] Parsing only physical numbers to an array in C

查看:98
本文介绍了仅将物理数字解析为C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在Cto中创建一个只包含大于零的正数的数组吗?与 unsigned 类型的 int 类似,但是在数组中。



当我将元素解析到数组中时,我有以下代码进行检查但是我认为这检查它1)缓慢完成处理,2)是检查错误的方法。

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.

[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);
}

推荐答案

检查总是值得的:它会在以后挽救很多悲伤!



代码一点都不差 - 它可能会使用多数组访问代码的处理,但编译器可能会优化它。

您可以尝试

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
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.


这篇关于仅将物理数字解析为C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆