你如何获得传递给函数的数组的大小? [英] How do you get the size of array that is passed into the function?

查看:46
本文介绍了你如何获得传递给函数的数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来打印出数组中的元素.但是,当我处理传递的数组时,我不知道如何遍历数组.

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?

推荐答案

您还需要将数组的大小传递给函数.
当您将数组传递给函数时,您实际上是在传递该数组中第一个元素的地址.所以指针只指向函数内部的第一个元素.

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.

由于数组中的内存是连续的,您仍然可以使用诸如(b+1)之类的指针算法来指向第二个元素或等效的b[1]

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])

... 和 数组不是与指针相同.

这篇关于你如何获得传递给函数的数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆