View previous topic :: View next topic |
Author |
Message |
tandy Guest
|
How to check if array is full |
Posted: Tue Jun 17, 2008 5:05 pm |
|
|
Hi,
I am a beginner,
How do I check if my array is full or not?
Code: |
int array[96];
//then i put some data onto it
if( condition) // to check if the array is full or not
{}
|
It would be highly appreciated if someone could help me do this.
Thank You
Tandy |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Jun 18, 2008 12:06 am |
|
|
Normally you know this, because you (the programmer) are incrementing
an index into the array. The number of elements is the same as the
current value index.
Or, if you use strcpy() to copy a string into the array, you can use
strlen() to find the length of the string. Though, ideally, you would check
the length before you copy it into the array, to make sure that you don't
write beyond the end of the array.
If this doesn't answer your question, then you need to give more details
about how you are declaring the array and how you are writing to it. |
|
|
libor
Joined: 14 Dec 2004 Posts: 288 Location: Hungary
|
|
Posted: Wed Jun 18, 2008 9:18 am |
|
|
Just to clear things up a little (or confuse you more..)
There's no such thing as an "empty" (or half-full) array.... Your array is always "full'. When you declare it, it is already full of garbage bytes (or zeroed out if you have cleared the memory)
As PCM Programmer says you can however keep track of what part of the data useful to you in the array, and what are the locations that contain useless (not more needed) 'garbage' data (you can call it empty space) that you can use for storing new data.
It is up to your code to do it. |
|
|
John P
Joined: 17 Sep 2003 Posts: 331
|
|
Posted: Wed Jun 18, 2008 11:34 am |
|
|
Are we to assume that the array index gets incremented every time you load an element?
One way to check for array-full, or at least get somewhat close to doing it, is to work with a defined value for the array size and then check for it:
Code: |
#define ARRAY_SIZE 96
int array[ARRAY_SIZE];
if(index >= ARRAY_SIZE) // to check if the array is full or not
{ // Handle the full condition
}
// OK, then i put some data onto it
array[index] = my_new_data;
index++; // Increment, ready for next time
|
Note "defensive programming" use of the >= compare. You wouldn't want a situation where the index went above 96 for some reason and you were unable to detect it. |
|
|
|