通过未知长度的int数组迭代

时间:2013-02-22 00:25:01

标签: c microcontroller

我正在尝试遍历一个包含最多最多4个元素的数组 - 不存在数组长度的其他知识。

伪代码

void insert_vals(uint8_t num, uint8_t *match_num, uint8_t *value)
{
    uint8_t i;

    while(data_exists)  // how do I determine if data exists in 'value'?
    {
        switch(num)
        {
            case 0:
            {
                switch(match_num[i])
                {
                    case 0:
                        hw0reg0 = value[i];
                    case 1:
                        hw0reg1 = value[i];
                    case 2:
                        hw0reg2 = value[i];
                    case 3:
                        hw0reg3 = value[i];
                }
            }
            case 1:
            {
                switch(match_num[i])
                {
                    case 0:
                        hw1reg0 = value[i];
                    case 1:
                        hw1reg1 = value[i];
                    case 2:
                        hw1reg2 = value[i];
                    case 3:
                        hw1reg3 = value[i];                 
                }
            }
            // etc. 2 other cases
        }
        i++;
    }
}

调用示例(伪代码)

/*
 * num: hardware device select from 1 - 4
 * match_num: 4 possible matches for each hardware device
 * value: 32-bit values to be assigned to 4 possible matches
 * NOTE: This function assumes hardware devices are selected
 * in a consecutive order; I will change this later.
 */

 // example calling code - we could have configured 4 hardware devices
 insert_vals(0, [0, 1], [0x00000001, 0x000000FF]);  // arg2 and arg3 equal in length

我怎样才能做到这一点?

在字符数组中,C会自动将'\0'添加到数组的末尾,但这似乎不是整数数组的情况。如果我在某种程度上能够在运行时确定match_numvalue(请参阅if语句)的长度,那么这将允许我创建一个for循环。 / p>

修改

因为我知道最多会有4个元素,所以我不能做类似以下的事情吗?

void insert_vals(uint8_t num, uint8_t *match_num, uint32_t *value)
{
    int i;

    for(i = 0; i < 4; i++)
    {
        if(value[i] == -1)
            break;
        else
        {
            // Assign data
        }
    }
}

2 个答案:

答案 0 :(得分:3)

只有指针才能获得指向数组的长度。您必须传递长度,或者它必须是常量(总是4),在未使用的元素中有一些sentinel值 - 这个值在某种程度上对您的计算无效(比如NUL用于字符串)。

答案 1 :(得分:1)

是否有值可以保证它不在“可用”数据中? (例如0对于字符串没有有效字符,因此Kernighan先生和Ritchie先生决定选择它作为“数组末尾”标记。你可以对任何值做同样的事情。

假设您知道您的整数值介于0到512之间,因此您可以初始化整个数组,例如到1024,然后填充它并迭代它直到出现一个> 512的数字(必须是你的数组标记的结尾)。

另一种可能性是将数组中的元素数与数组一起传递。

相关问题