Home > Back-end >  C how to acquire the array elements' real 'number
C how to acquire the array elements' real 'number

Time:09-16

C code is as follows:


#include
{
Int arr [10]={0};
}

Define a named arr and can hold 10 integer array of data, part has been initialized values. But I want to know the number of actual element in the array, which is number 3 (1, 2, 3), how can I use code implementation.

CodePudding user response:

It might be a method ha:
Initialization time assign special values (impossible to obtain values, such as you want to store is positive, negative, the initialization time assignment such as 1), the need to get the number of array elements, traversal, to know the actual number,
The trouble is, every time to use arrays, need to be initialized.

CodePudding user response:

Only his record for you, you is the length of the actual 10, you took three inside, the rest of the default 0 useless,

CodePudding user response:

Oneself maintain a variable record how many elements are
At first, how many of the array is initialized to how much
Add an element is
An element is less minus 1

CodePudding user response:

This is no interface, for defining such an array, in addition to the first three initialization, behind, which has not been initialized values default is 0.
How many valid data array, the need to maintain and preserve,

CodePudding user response:

The
refer to the building program small white's reply:
C code is as follows:


#include
{
Int arr [10]={0};
}

Define a named arr and can hold 10 integer array of data, part has been initialized values. But I want to know the number of actual element in the array, which is number 3 (1, 2, 3), excuse me how to use the code to achieve.



 # include & lt; Stdio. H> 
{
Int arr [10]={0};
int num=0;
for(int i=0; i<10; I++) {
[I] if (arr) num++;//array initialization, assignment of those will be zero filling, statistics the number of non-zero Numbers can
}
}

CodePudding user response:

A simple array doesn't work, only two ways:
1, specify the agreement, choose no value as an "empty sign" , if all the stored data is positive, but not beyond the scope of int, then can use negative Numbers such as 1 agreement as empty, array need to initialize, delete remember need to assign values to 1, the number of statistical when not to 1,
 
{
int i;
For (I=0; I & lt; 10; + + I) {
Arr [I]=1;
}
}


2, custom structure, add the length of the record, if access value is negative, then there will be no other Numbers can be used as a marker, the need to add additional variables to record length, relatively simple, such as
 
Typedef struct {
Int the list [10];
Unsigned int len.
} Array_t;
Array_t Array={0};
{
//in the
Array. The list [Array. Len++]=1;
//remove
The int Value=https://bbs.csdn.net/topics/Array.list [Array. Len -- --];
//statistics
Int CalLen=Array. Len;
}

  • Related