Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the size of array that is passed into the function?

Tags:

arrays

c

I am trying to write a function that prints out the elements in an array. However when I work with the arrays that are passed, I don't know how to iterate over the array.

void
print_array(int* b)
{
  int sizeof_b = sizeof(b) / sizeof(b[0]);
  int i;
  for (i = 0; i < sizeof_b; i++)
    {
      printf("%d", b[i]);
    }
}

What is the best way to do iterate over the passed array?

like image 406
unj2 Avatar asked Oct 06 '10 01:10

unj2


People also ask

How do you find the size of an array passed to a function in C?

Using the sizeof() operator and using pointer arithmetic. The sizeof() operator in C calculates the size of passed variables or datatype in bytes. Therefore to find the array's length, divide the total array size by the size of one datatype that you are using.

How do I get the size of an array?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

When array is passed to function and is passed?

In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.

How do you get the size of an array in Python?

To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.


2 Answers

You need to also pass the size of the array to the function.
When you pass in the array to your function, you are really passing in the address of the first element in that array. So the pointer is only pointing to the first element once inside your function.

Since memory in the array is continuous though, you can still use pointer arithmetic such as (b+1) to point to the second element or equivalently b[1]

void print_array(int* b, int num_elements)
{
  for (int i = 0; i < num_elements; i++)
    {
      printf("%d", b[i]);
    }
}

This trick only works with arrays not pointers:

sizeof(b) / sizeof(b[0])

... and arrays are not the same as pointers.

like image 97
Brian R. Bondy Avatar answered Sep 28 '22 07:09

Brian R. Bondy


Why don't you use function templates for this (C++)?

template<class T, int N> void f(T (&r)[N]){
}

int main(){
    int buf[10];
    f(buf);
}

EDIT 2:

The qn now appears to have C tag and the C++ tag is removed.

like image 26
Chubsdad Avatar answered Sep 28 '22 09:09

Chubsdad