c语言数组不确定长度_如何在C中确定数组的长度

c语言数组不确定长度

C does not provide a built-in way to get the size of an array. You have to do some work up front.

C没有提供获取数组大小的内置方法。 您必须先做一些工作。

I want to mention the simplest way to do that, first: saving the length of the array in a variable. Sometimes the simple solution is what works best.

我想提一下最简单的方法:首先将数组的长度保存在变量中。 有时,简单的解决方案是最有效的方法。

Instead of defining the array like this:

而不是像这样定义数组:

int prices[5] = { 1, 2, 3, 4, 5 };

You use a variable for the size:

您使用一个变量作为大小:

const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };

So if you need to iterate the array using a loop, for example, you use that SIZE variable:

因此,例如,如果您需要使用循环来迭代数组,请使用该SIZE变量:

for (int i = 0; i < SIZE; i++) {
  printf("%u\n", prices[i]);
}

The simplest procedural way to get the value of the length of an array is by using the sizeof operator.

获取数组长度值的最简单的过程方法是使用sizeof运算符。

First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

首先,您需要确定数组的大小。 然后,您需要将其除以一个元素的大小。 之所以起作用,是因为数组中的每个项目都具有相同的类型,并且具有相同的大小。

Example:

例:

int prices[5] = { 1, 2, 3, 4, 5 };

int size = sizeof prices / sizeof prices[0];

printf("%u", size); /* 5 */

Instead of:

代替:

int size = sizeof prices / sizeof prices[0];

you can also use:

您还可以使用:

int size = sizeof prices / sizeof *prices;

as the pointer to the string points to the first item in the string.

因为指向字符串的指针指向字符串中的第一项。

翻译自: https://flaviocopes.com/c-array-length/

c语言数组不确定长度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值