Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

c - Get the number of elements that it has a value in array

I have an array like the following

int arr[32];

This array can contain 32 element.
If I added into that array some data like the following

arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;

As you see I added data into elements 0,1,2,3 and the other elements is still not initialized or empty.

Now, how to get the elements count that has only data ?

in current example will get 4 elements.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this in multiple ways - one is to keep counter of initialized values:

arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
n = 4;

This only works if you will fill array sequentially.

Other way is to initialize array with some value which semantically can't be elements of the array:

int arr[32] = {-1};

After that, you can check if the current element contains value different than -1.

The sample loop could be implemented like this:

for(i = 0; i < 32 && arr[i] != -1; i++)
{
   // do things
}

Also, as @Jongware pointed out in the comment - if you don't mind spending O(n) of extra space - you could have additional flag array:

int fill[32] = {0};
arr[0] = 5;   fill[0] = 1;
arr[1] = 10;  fill[1] = 1;
arr[2] = 15;  fill[2] = 1;
arr[3] = 20;  fill[3] = 1;

You could save some space using bitsets, if that is important for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...