本文共 1465 字,大约阅读时间需要 4 分钟。
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.
因为指向字符串的指针指向字符串中的第一项。
翻译自:
c语言数组不确定长度
转载地址:http://uvqgb.baihongyu.com/