1

我正在尝试遍历一个最多包含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_numand value(参见if语句)的长度,那么这将允许我创建一个for循环。

编辑

既然我知道最多有 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
        }
    }
}
4

2 回答 2

3

仅给定指针,您无法获得指向的数组的长度。要么你必须传递长度,要么它必须是常数(总是 4),并且在未使用的元素中有一些标记值——这个值在某种程度上对你的计算是无效的(比如 NUL 是用于字符串的)。

于 2013-02-22T00:28:47.910 回答
1

是否有一个值可以保证它不在“可用”数据中?(例如,0 不是字符串的有效字符,因此 Kernighan 先生和 Ritchie 先生决定选择它作为“数组结尾”标记。您可以对任何值执行相同的操作。

假设您知道您的整数值介于 0 到 512 之间,因此您可以将整个数组初始化为 1024,然后填充它并遍历它,直到出现 >512 的数字(这必须是您的数组结束标记)。

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

于 2013-02-22T00:31:04.563 回答