博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c语言数组不确定长度_如何在C中确定数组的长度
阅读量:2503 次
发布时间:2019-05-11

本文共 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/

你可能感兴趣的文章
冲刺Noip2017模拟赛3 解题报告——五十岚芒果酱
查看>>
并查集
查看>>
sessionStorage
查看>>
代码示例_进程
查看>>
Java中关键词之this,super的使用
查看>>
人工智能暑期课程实践项目——智能家居控制(一)
查看>>
前端数据可视化插件(二)图谱
查看>>
kafka web端管理工具 kafka-manager【转发】
查看>>
获取控制台窗口句柄GetConsoleWindow
查看>>
Linux下Qt+CUDA调试并运行
查看>>
51nod 1197 字符串的数量 V2(矩阵快速幂+数论?)
查看>>
OKMX6Q在ltib生成的rootfs基础上制作带QT库的根文件系统
查看>>
zabbix
查看>>
多线程基础
查看>>
完美解决 error C2220: warning treated as error - no ‘object’ file generated
查看>>
使用SQL*PLUS,构建完美excel或html输出
查看>>
SQL Server数据库笔记
查看>>
X-Forwarded-For伪造及防御
查看>>
android系统平台显示驱动开发简要:LCD驱动调试篇『四』
查看>>
Android 高仿微信头像截取 打造不一样的自定义控件
查看>>