C语言 c - 如何在c中打印数组的最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44130392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:39:52  来源:igfitidea点击:

How do I print the last element of an array in c

carrays

提问by gerrard2461

I want to detect the last element of an array of integer in C code. Otherwise i need to stop handling array data when the array element is empty. really my array have a maximum size fixed and it was filled from an external file so i dont know when it stop filling the array.

我想检测 C 代码中整数数组的最后一个元素。否则,当数组元素为空时,我需要停止处理数组数据。真的,我的数组有固定的最大大小,它是从外部文件填充的,所以我不知道它何时停止填充数组。

回答by Pras

There is no defined term as empty array

没有定义的术语为空数组

Your array will always hold some value even if you dont initialize it explicitly

即使您没有显式初始化它,您的数组也将始终保留一些值

You need to define in your application how will you term it as empty may be by considering if its(element of array) value is 0 or some other value

您需要在您的应用程序中定义如何通过考虑它的(数组元素)值是 0 还是其他值来定义它为空

回答by Ollaw

Last element is in position

最后一个元素就位

sizeof(array)/sizeof(array[0]) - 1

回答by haltode

If you don't explicitly know the size of your array, you could calculate it by using the sizeofoperator:

如果您不明确知道数组的大小,则可以使用sizeof运算符来计算它:

size_t size = sizeof(your_array) / sizeof(your_array[0]);

This calculates the total size in bytes of the array and divides it by the size of one element (you can also use sizeof(int)in your case, but if you change the type of your array this will probably break).

这将计算数组的总大小(以字节为单位)并将其除以一个元素的大小(您也可以sizeof(int)在您的情况下使用,但如果您更改数组的类型,这可能会中断)。

Then, you can simply loop over the array's elements like so:

然后,您可以简单地循环数组的元素,如下所示:

for(size_t i = 0; i < size; ++i)
    printf("%d\n", your_array[i]);

回答by Osman Gani Khan Masum

Why not you use the simple n-1method!

为什么不使用简单的n-1方法!

Just let a variable l

只是让一个变量 l

where l = arr[n - 1];

在哪里 l = arr[n - 1];

then printf(l)...

然后printf(l)……

Quite simple I guess...

很简单,我猜...