0

How to find the sizeof an array, by a function which receives only a pointer to the array?


    int find(int *p)
{  
// I want  to find  the  sizeof  
//   the array in this function  


    return 1;  
}

    int main()

{

    int a[]={12,2,9,6,5,11,15};
    find(a);

    return  0;
}
user2713461
  • 387
  • 2
  • 5
  • 16

2 Answers2

2

Unless you pass the size of the array you can't do it. If, in your case, -1 is a sentinel marking the end of the list you can use this:

#include <stdio.h>

int find(int *p)
{  
    int * q = p;
    while(*q != -1)
        ++q;
    return q-p;  
}

int main()
{

    int a[]={12,2,9,6,5,11,-1};
    printf("%d", find(a));

    return  0;
}
dcaswell
  • 3,137
  • 2
  • 26
  • 25
  • i did not understand.. int *q =p; why did u use it?? and also why did you return q-p?? – user2713461 Aug 25 '13 at 15:38
  • If -1 only appears at the end of the array, and always appears at the end of the array, then the code I supplied will return the count of items. – dcaswell Aug 25 '13 at 15:39
  • ok. but why are you returning q-p?? – user2713461 Aug 25 '13 at 15:40
  • *q is a shorthand for q[0]. Since q keeps increasing through the loop you're testing q[0], q[1], q[2], etc. which is like testing a[0], a[1], a[2] until you get the place in the array where -1 occurs. – dcaswell Aug 25 '13 at 15:41
2

If you are just passing a pointer with no size information to find then you have to have to use something like the C char* string idiom and have a special end-of-data value. C's string idiom uses the null character (\0) mark the end-of-data. C's standard length-of-string function (strlen) also doesn't include this null character in the count of the size of the string. It looks like the above code may be using -1 to mark the end of data. This will work if you never use negative values for data. If this is the case, then you can calculate the size of array like this:

size_t length_of_array(int *p) {
    size_t len = 0;
    while( *(p + len) > 0 )
        ++len;
    return len;
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • i have not used -1 as end, if i dont know the last character, how to proceed?? – user2713461 Aug 25 '13 at 15:32
  • 1
    You can't. You are passing a pointer, not an array, and there's no way to get the number of elements of an array given a pointer a pointer to the array. Is there an *actual* problem you're trying to solve? – Nik Bougalis Sep 02 '13 at 13:09