Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if an array position exist?

Tags:

c

char X[3];

how to check if array X[position] exist? for example:

if (x[4] == True)
    printf("Exists")
else 
   printf("NONE")
like image 678
user422100 Avatar asked Apr 24 '11 16:04

user422100


People also ask

How do you find array position?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you check if a value in an array exists C?

To check if given Array contains a specified element in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.

How do I check in JavaScript if a value exists at a certain array index?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.

How do you check if an array exists in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

Each position in a C array, within the array's bounds, always exists, so there's no need for a way to check a random position for existence. All you need to do is make sure that the index is inside the bounds.

If the array is declared with a static size, you can get the length of the array via sizeof:

int array[30];
int length = sizeof(array) / sizeof(int);
// sizeof(array) returns the size in bytes, divide by element size to get element count

However if the array doesn't have a known length at compile time, you'll have to find it out in some other way. C functions dealing with arrays usually take in both a pointer to the first element and the size as separate arguments.

void do_something_to(int *items, int item_count);

You need to be especially careful when passing arrays to functions, since an array passed to a function becomes a "plain pointer" and the compiler loses all track of its size (sizeof will report the size of the pointer). IMHO it's least confusing to avoid array arguments altogether and just stick to pointers.

like image 91
Matti Virkkunen Avatar answered Nov 10 '22 15:11

Matti Virkkunen