C 数组中有多少个元素已满

发布于 2024-08-22 19:33:54 字数 34 浏览 6 评论 0原文

如果你有一个 C 语言数组,你如何知道它被填充了多少?

If you have an array in C, how can you find out how much of it is filled?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

记忆里有你的影子 2024-08-29 19:33:54

在 C 数组中,任何元素都是对象。它不像在 Java 中,首先必须分配引用以指向对象。 C 中的任何内容的行为都类似于 Java 中的原始类型。

如果您在 C 中有一个指针数组,您可能会认为这与 Java 中的工作方式类似。您可以使用空指针来指定“未填充指向对象”:

// creates an array of 10 pointers, and initializes all of
// them to null pointers. If you leave off "{ 0 }", you 
// have to manually initialize them!
struct foo *array[10] = { 0 };

然后您可以简单地测试

if(array[i] == 0) {
  printf("Position %d does not point to an object!\n", i);
}

In a C array, any element is an object. It's not like in Java where you have references that first have to be assigned to point to objects. Anything in C behaves like a primitive type in Java.

If you have an array of pointers in C, you may view this similar to how things in Java work. You can use null pointers to designate "is not filled to point to an object":

// creates an array of 10 pointers, and initializes all of
// them to null pointers. If you leave off "{ 0 }", you 
// have to manually initialize them!
struct foo *array[10] = { 0 };

Then you can simply test with

if(array[i] == 0) {
  printf("Position %d does not point to an object!\n", i);
}
耳钉梦 2024-08-29 19:33:54

您需要自己跟踪这一点。没有“完整”的概念(或介于两者之间的任何概念):你必须定义它。

当然,如果数组中的元素是连续的,您可以使用 NULL 元素来表示数组的“结束”,从而同时定义“完整”状态。

You need to keep track of this yourself. There is no concept of "full" (or anything in between for that matter): you have to define this.

Of course if the elements are contiguous in the array, you could use a NULL element to signify the "end" of the array thus defining a "full" state at the same time.

与他有关 2024-08-29 19:33:54

它都已满,所以答案是无论你的数组的大小是多少。数组是一个连续的内存段,因此默认情况下它会填充该内存位置之前的内容。

但您可能想知道其中有多少是您关心的数据,而不是随机数据。在这种情况下,除非您自己跟踪,否则无法知道这一点。

It's all filled, so the answer is whatever the size of your array is. An array is a contiguous memory segment, so it is filled by default with whatever was at that memory location before.

But you probably want to know how much of it is filled with data that you care about, and not with random data. In that case, there is no way of knowing that unless you keep track of it yourself.

瑕疵 2024-08-29 19:33:54

我同意其他答案,但我可以建议您一种使您的工作更轻松的方法。您可以像对象一样管理数组并控制数据的添加和删除。如果您实现两个函数,一个用于添加元素,一个用于删除元素,并使用适当的逻辑来管理碎片和多线程,则可以跟踪数组中元素的数量并读取计数器,该计数器仅由 add 和 remove 写入功能。因此,您不必每次需要计算元素时都执行循环。

I agree with other answers, but I can suggest you a way to make your work easier. You can manage the array like an object and control the adding and the removing of data. If you implement two functions, one to add elements and one to remove them, with the proper logic to manage fragmentation and multi-threading, you can track the number of elements into the array reading a counter, which is written only by add and remove function. So you don't have to execute a loop every time you need to count the elements.

颜漓半夏 2024-08-29 19:33:54

从C语言的角度来看,不存在“填充”的概念。一旦定义了数组,就会为其分配内存。对于像 array1 这样的数组(参见下面的示例),元素被初始化为 0。但是,对于像 array2 这样的数组,元素可以具有随机值。

因此,“填充”的概念必须由程序提供。一种可能的“带内”方式是:
(a) 选择元素类型的一个特定值(例如 0xFFFFFFFF)并用它来检测每个数组元素的填充/空属性(但是,要意识到这种方法会从元素集中夺走一个其他有效值。),并且
(b) 在程序范围内的适当位置将数组的所有元素“初始化”为不允许的值。
(c) 要查找数组填充级别,请计算有效元素的数量。

$ cat t2.c
#include <stdio.h>
#define N 10

typedef unsigned long int T;

static const T EmptyElementValue = 0xFFFFFFFF;
// Choose any suitable value above. However, the chosen value
// would not be counted as an "empty" element in the array.

static T array1[ N ];

void
printArray( T a[], size_t length )
{
    size_t i;
    for( i = 0; i < length; ++i )
    {
        printf( "%lu, ", a[ i ] );
    }
    printf( "\n" );
}

size_t
numFilledElements( T a[], size_t length )
{
    size_t fillCount = 0;
    size_t i;

    for( i = 0; i < length; ++i )
    {
        if( a[ i ] != EmptyElementValue )
        {
            fillCount += 1;
        }
    }

    return fillCount;
}

int main()
{
    T array2[ N ];
    size_t i;

    printArray( array1, N );
    printArray( array2, N );

    //------------------------------------------//

    // Make array2 empty
    for( i = 0; i < N; ++i )
    {
        array2[ i ] = EmptyElementValue;
    }

    // Use some elements in array2
    array2[ 2 ] = 20;
    array2[ 3 ] = 30;
    array2[ 7 ] = 70;
    array2[ 8 ] = 80;

    printf( "Number of elements \"filled\" in array2 = %u\n",
        numFilledElements( array2, N  ));

    // Stop using some elements in array2
    array2[ 3 ] = EmptyElementValue;

    printf( "Number of elements \"filled\" in array2 = %u\n",
        numFilledElements( array2, N ) );


    return 0;
}


$ gcc -Wall t2.c -o t2


$ ./t2
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 60225, 2280452, 1627469039, 1628881817, 2281060, 2280680, 1628304199, 1628881818, 47, 
Number of elements "filled" in array2 = 4
Number of elements "filled" in array2 = 3

$

From the C language perspective, there is no concept of "filled". Once an array is defined, memory is allocated to it. For arrays like array1 (see example below), elements get initialized to 0. However, for arrays like array2, the elements can have random value.

So, the notion of "filled" has to be supplied by the program. One possible to "in-band" way is to:
(a) Choose one specific value of the element type (e.g. 0xFFFFFFFF) and use it to detect fill/empty property of each array element (However, realize that this approach takes away one otherwise valid value from the element set.), and
(b) "initialize" all the elements of the array to that disallowed value at suitable position in the program scope.
(c) To find array fill level, count the number of valid elements.

$ cat t2.c
#include <stdio.h>
#define N 10

typedef unsigned long int T;

static const T EmptyElementValue = 0xFFFFFFFF;
// Choose any suitable value above. However, the chosen value
// would not be counted as an "empty" element in the array.

static T array1[ N ];

void
printArray( T a[], size_t length )
{
    size_t i;
    for( i = 0; i < length; ++i )
    {
        printf( "%lu, ", a[ i ] );
    }
    printf( "\n" );
}

size_t
numFilledElements( T a[], size_t length )
{
    size_t fillCount = 0;
    size_t i;

    for( i = 0; i < length; ++i )
    {
        if( a[ i ] != EmptyElementValue )
        {
            fillCount += 1;
        }
    }

    return fillCount;
}

int main()
{
    T array2[ N ];
    size_t i;

    printArray( array1, N );
    printArray( array2, N );

    //------------------------------------------//

    // Make array2 empty
    for( i = 0; i < N; ++i )
    {
        array2[ i ] = EmptyElementValue;
    }

    // Use some elements in array2
    array2[ 2 ] = 20;
    array2[ 3 ] = 30;
    array2[ 7 ] = 70;
    array2[ 8 ] = 80;

    printf( "Number of elements \"filled\" in array2 = %u\n",
        numFilledElements( array2, N  ));

    // Stop using some elements in array2
    array2[ 3 ] = EmptyElementValue;

    printf( "Number of elements \"filled\" in array2 = %u\n",
        numFilledElements( array2, N ) );


    return 0;
}


$ gcc -Wall t2.c -o t2


$ ./t2
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 60225, 2280452, 1627469039, 1628881817, 2281060, 2280680, 1628304199, 1628881818, 47, 
Number of elements "filled" in array2 = 4
Number of elements "filled" in array2 = 3

$
不气馁 2024-08-29 19:33:54

从数组的大小中减去空元素的数量。 ;-)

抱歉,没有办法(除非您跟踪)来判断数组元素是否已被修改。

Subtract the number of empty elements from the size of the array. ;-)

Sorry, there is no way (except you keeping track), to tell whether an array element has been modified.

太阳男子 2024-08-29 19:33:54

在 C 中,没有内置方法可以知道有多少元素填充了您关心的数据。您需要自己构建它。如前所述,如果您可以拥有一个不代表任何内容的值(例如 0),您可以:

  1. 计算不具有此未定义值的元素。
  2. 如果填充的元素位于同一内存块中,则可以查找未定义的值(哨兵)。

另一方面,如果需要表示数据的范围,则需要一个标志数组来跟踪设置的元素和未设置的元素的数量:

例如,如果您有一个包含 32 个或更少元素的数组,则只需要一个无符号整数来跟踪您的数组:
1100010 ...

值:

1 ->设置

2->设置

3 ->没有设置

4 ->未设置

5->未设置

6 -> ,每当您填充元素时,

因此

您都会调用设置正确位的函数,而当您“取消填充”数据时,您会取消设置与其相对应的位。

完成此操作后,您需要做的就是简单地调用 popcount 超过标志数组。

in C, there is no built-in way of knowing how many elements are filled with data that you care about. You will need to build it yourself. As was previously said, if you can have a value that will not represent anything(0 for example), you could :

  1. Count the elements that do not have this undefined value.
  2. If your filled elements will be in the same block of memory, you can look for the undefined value(Sentinel)

On the other hand, if you need the extent of your data to be represented, You will need a flag array that will keep track of the elements that are set and those that aren't :

For example, if you have an array of 32 elements or less, you only need an unsigned integer to keep track of your array:
1100010 ...

Values:

1 -> Set

2 -> Set

3 -> no set

4 -> not set

5 -> not set

6 -> set

etc.

So Whenever you are filling an element you call the function that sets the correct bit and when you are "unfilling" the data you unset the bit that corresponds to it.

Once this is done, All you would need to do is simply call a popcount over the flag array.

独行侠 2024-08-29 19:33:54

您可以执行一个 while(yourArray != NULL) 循环,并通过循环仅增加一个整数值,这应该会告诉您。

You could do a while(yourArray != NULL)loop and through the loop just increment an integer value and that should tell you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文