Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing arrays into a function,

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
0
0
US
Code:
int main()
{
   int my_arr[3] = {1, 2, 3};
   ....
   my_fun(my_arr);
}

void my_fun(int array[])
{
  /*need to determine the number of elements in array*/
  x = num_of_items_in_array;
  /*perform computation*/
}

It so happens that there is no clear way to determine the num of items in a passed array, since integer arrays are not null terminated.

Can anyone help me here? Or would I have to explicitly tell the function how many items are there int he given array?



 
I believe you will need to tell the function the number of elements :

Code:
int main()
{
   int my_arr[3] = {1, 2, 3};
   ....
   my_fun(&my_arr[0], 3);
}

void my_fun(int* piArray, int iArrayLen)
{
  /*need to determine the number of elements in array*/
  x = num_of_items_in_array;
  /*perform computation*/
}

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Code:
int main(void) {
int arrayname[5] = {1,2,3,4,5};
int wrongnum[20] = {1,2,3,4,5,6,7,8,9,0};
                   printf("arrayname = %d elements\nwrongnum = %d elements\n",asz(arrayname),asz(wrongnum));
		   return 0;
}

Of course if you want an accounting of the actual number
of valid entries in the array according to whatever criteria you will have to devise that yourself.

HTH
 
Oops..the asz macro...
Code:
#define asz(a) ((sizeof(a) / sizeof(a[0])))
 
Be careful: don't use asz macros in function body!
Code:
void my_fun(int array[],...)
/* sizeof(array) treated as a pointer size! */
So read sedj's adivice again. You can't obtain array argument size via its parameter only (in C and C++).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top