is there any way to test to see if an element of an array exists in c?
I am passing an array into a function in c and i want to make sure that I am writing to an existing element.
is there any way to test to see if an element of an array exists in c?
I am passing an array into a function in c and i want to make sure that I am writing to an existing element.
There is no such way - you need to pass the size of the array to the function so your function knows how large the array is.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
ooo i can just use
if (array[i] != NULL)
EDIT: oh .. nvm
No.
(When passed into a function, an array is turned into just a pointer to the first element; if you want to know the size, you must pass that in to the function separately.)
Well, you CAN if you can guarantee that the last element in the array is always NULL and nothing else in the array is. It is perfectly valid to not pass in the array size if you have a "sentinel" or "end-marker" to indicate the end of the array.
However, you have to be careful that you do not prevent valid values from being used in the array. An array of unsigned integers that could hold any value would not be possible to do this with, since ALL values would potentially be used.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
would this work to find the end of an array... assuming there are no '\0' in the array
Code:uInt8 *image = NULL; FunctionICantSeeInsideOf((void *) &image); for(i=0; i<(10000000); i++){ if(image[i] == '\0') { lengtharray = i; goto over; } } over: return lengtharray
Yes, the use of a "marker" to indicate the end is one way to indicate how long a sequence of data is. However, unless "FunctionICantSeeInsideOf" is putting a the correct marker at the end of the array, you can't use this sort of mechanism.
And your use of "goto" is completely avoidable and "useless", since "break" is shorter to type and more acceptable. Alternatively, just use "image[i]" as part of the end condition of the for-loop, and set lengtharray after the loop.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.