如何在for循环条件下正确使用`sizeof`运算符? [英] How to use `sizeof` operator inside the condition of for-loop properly?

查看:88
本文介绍了如何在for循环条件下正确使用`sizeof`运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for循环的条件是否总是需要常数?
如何在其中放置 sizeof 函数以运行显示数组所有元素的输出?

Do the conditions of the for-loop always need constant? How can I put sizeof function there to run an output showing all the elements of an array?

#include<iostream>
using namespace std;

void array_output(int a[])
{
    for (int i = 0; i < (sizeof(a)) / (sizeof(a[0])); i++)
    {
        cout << a[i] << endl;
    }
}

int main()
{
    int a[] = { 22, 53, 13, 65, 80, 31, 46 };
    array_output(a);
    return 0;
}




  • i<(sizeof(a) 输出显示第一个 4 元素

  • i<(sizeof(a))/(sizeof(a [0])) 输出仅显示元素
  • 7 时,
  • 代替 sizeof 直接用作条件,它会给

    正确的输出,显示所有元素

    • i<(sizeof(a) output shows first 4 elements
    • i<(sizeof(a))/(sizeof(a[0])) output shows only the first element
    • instead of sizeof when 7 is directly used as a condition, it gives
      the right output, showing all the elements.
    • 推荐答案

      如果在 sizeof 运算符中使用实际数组,则将获得数组的大小以字节为单位,这意味着您可以使用 sizeof(array)/ sizeof(array_type)计算您期望的元素数。

      If you use the actual array in the sizeof operator you will get the size of the array in bytes, meaning you can calculate the number of elements like you expected it using sizeof(array) / sizeof(array_type).

      int x[] = {1, 1, 1, 1, 1, 1};    
      int sum = 0;
      
      for (int i = 0; i < sizeof(x) / sizeof(int); i++)
          sum += x[i];
      
      // sum == 6
      

      但是如果将数组作为函数参数传递,则会遇到指针衰减。这意味着数组大小信息将会丢失,而您将获得指针大小,这就是您描述的行为。

      However if you pass the array as a function parameter you will encounter pointer decay. This means that the array size information is lost and you get the pointer size instead, which is the behavior that you described.

      int sum(int arr[])  // arr decays to int*
      {
          int sum = 0;
      
          for (int i = 0; i < sizeof(arr) / sizeof(int); i++)
              sum += arr[i];
      
          return sum;
      }
      
      int main() 
      {   
          int x[] = {1, 1, 1, 1, 1, 1};    
          return sum(x);  // will return 1 or 2, depending on architecture
      }
      

      #include <cstddef>
      
      template <std::size_t N>
      int sum(int (&arr)[N])
      {
          int sum = 0;
      
          for (int i = 0; i < N; i++)
              sum += arr[i];
      
          return sum;
      }
      
      int main() 
      {   
          int x[] = {1, 1, 1, 1, 1, 1};    
          return sum(x);  // will return 6
      }
      

      这篇关于如何在for循环条件下正确使用`sizeof`运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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