Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use span to solve array degeneration and cross-boundary access

Shulou Source: shulou.com Published: 2022-06-02 00:28:31 10月02日 Update

This article is about how to use span to solve array degradation and cross-boundary access. I think it is very practical, so I share it with you. I hope you can get something after reading this article.

Array is a feature that C++ inherits from C language. It is easy to use and can provide excellent performance, so it is widely used. But the other side of simplicity is risk, and the two biggest problems are array decay and range errors. How to solve the problem of array degradation and out-of-bounds access by using span, the new feature of Clippers 20, in advance.

First, take a look at the most common code that uses arrays:

Int data [10]; for (size_t I = 0; I < sizeof (data) / sizeof (data [0]); + + I) {data [I] = 0;}

When the array is defined, there is also information about the number of elements. Use this information to manipulate the array. However, when an array is passed to a function as an argument, it can only be passed as a pointer, which is called array degeneration. In order to correctly grasp the size of the array, it is generally necessary to transfer the size information of the array at the same time. For example, the following initialization function is like this:

Void init_data (int buffer [], size_t size) {cout

Tags: Arrays parameters that is information functions at the same time size problems code elements forms next functions pointers more templates features knowledge articles C++ Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft NVidia Xiaomi MariaDB Redmi