On Oct 1, 6:29 am, Harshal Jain <
[email protected]> wrote:
if I have the code like
int arr[]={1,2,3};
int *arr1=arr;
then how can we get the length of array arr or arr1
I have tried the following but it's of no use
int length=0;
while(arr1!=NULL) // or while(*arr!='\0')
{
arr1++;
length++;}
why did you think the array would be either null or nul terminated?
As mentioned by Keith, the length of an array object can be computed
like this
sizeof(arr)/ sizeof(arr[0])
but this trick *won't* work with arr1 as it's a pointer
no it isn't. NULL is a macro that expands to a null pointer constant.
A string is terminated with a null character (sometimes referred to
as
nul). nul is not NULL. In particular the null pointer constant does
not
have to be all bits zero. Yeah wierd I know. Go and read the clc FAQ
for more details.
well it *might* if you were really unlucky. We can't say what it will
do.
don't quote sigs
Yeah correct so what should be the termination condition based on
which we can find end of the array (other than string)
Keith also said this:-
"Given a pointer to the first element of an array, you cannot compute
the length of the array without more information."
There is no way to do what you want. You either tag a special value
onto the end of the array which will never be mistaken for your data,
or (what I'd prefer) carry the length arounf with the array.
void process_stuff (int stuff [], size_t length);
some will say the use of array notation here is confusing.
I don't agree.