1) How to find array is empty in c . 2) How to find how many no of elements are filled in an array in c . | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

1) How to find array is empty in c . 2) How to find how many no of elements are filled in an array in c .

I prolly able to find answer 2 but how to find answer 1 . Eg - int arr[50] ; If nothing is inserted in this array then want to print arr[0]. I even tried to print that but nothing displayed . Help because this will help me to solve answer 2. For answer 2 scenario is int arr[50]; and eg already 5 elements are inserted out of 50 . But i don't know that it 5 or 20 elements in an array but i want write that code which will return that 5 or 20 elements are inserted in and array out of 50. I think sizeof tells you the size of array which I have tried from my end and tried to find empty element by comparing it to '\0'. This also doesn't work. So finally I am here for help .

13th Nov 2022, 9:38 AM
Om Yele
Om Yele - avatar
5 Answers
+ 1
Define empty. There is no such thing in C. You could initialize all elements of array to NULL and then check if element is not NULL. Although, I don't see the point. Related: https://www.sololearn.com/discuss/1857864/how-to-check-for-an-empty-array
13th Nov 2022, 10:33 AM
Mateusz Kempa
Mateusz Kempa - avatar
+ 1
You most likely will have to do all the bookkeeping chores by yourself, that's what was expected from a coder in C language anyway, the coder was expected to know what they're doing. An idea may involve a `struct` defined as custom type, where it carries a <counter> field which is used to count filled elements, and a pointer that can be initialized in time. Some functions might also be necessary to be created, for creating the `struct`, to add an element sequentially, remove (or replace) elements, release its memory block etc. You can use the `struct`'s <counter> field to answer the 2 questions.
13th Nov 2022, 12:14 PM
Ipang
+ 1
Om Yele here is a code snippet that demonstrates the idea. Every time you add an item to the array, the count variable increments. That way you know how many items were added. Conveniently, count also serves as the index of the next available location in arr. int count = 0; int arr[30]; arr[count++] = 5; arr[count++] = 10; arr[count++] = 6; arr[count++] = 2; printf("number of items in arr = %d", count); //Output: 4
13th Nov 2022, 7:00 PM
Brian
Brian - avatar
+ 1
Thankyou for your solution. I solved it .
14th Nov 2022, 2:32 AM
Om Yele
Om Yele - avatar
0
See i don't understand. PLZ help by providing code
13th Nov 2022, 12:16 PM
Om Yele
Om Yele - avatar