如何在一个元素为零的数组中查找元素数 [英] How to find number of elements in an array which has one of its element as zero

查看:44
本文介绍了如何在一个元素为零的数组中查找元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了一个包含30个元素的数组:-

I have declared an array of 30 elements as:-

unsigned char some_array[30];

我将一些元素存储在数组中,例如:-

I store some elements in the array, for eg:-

{0xFB, 0x07, 0x0B, 0x02, 0x00, 0x0C, 0x03, 0x08, 0x0F, 0x0F, 0x07, 0x0A, 0x09, 0x06, 0x0D}

我需要找到此数组中的元素数。

I need to find the number of elements in this array.

sizeof (some_array) / sizeof (some_array[0]); 

产生30,这是数组可以存储的元素总数。

yields 30, which is the total number of elements the array can store.

strlen(some_array);

收益4,即数组中0x00元素的索引。

yields 4, which is the index of 0x00 element in the array.

如何确定数组中存储的元素数量?

How can i determine the number of elements stored in the array ??

推荐答案

实际值,您可以在整个数组上执行 memset ,这将设置一个值,您确定该值不会属于初始化的值范围,例如0xff。然后执行 for 循环并计数。

Before assigning the actual values, you can do a memset on the entire array which would set a value you are sure won't be part of your initialized range of values, example 0xff. Then do a for loop and count.

int cnt = 0;
memset (some_array, 0xff, 30);

for (i = 0; i < 30; i++) {
    if (some_array[i] != 0xff) {
        cnt++;
    }
}

printf ("%d\n", cnt);

这篇关于如何在一个元素为零的数组中查找元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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