C将未知大小的数组传递给单个变量中的函数 [英] C Passing array of unknown size to a function in a single variable

查看:227
本文介绍了C将未知大小的数组传递给单个变量中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中,我必须将一个数组传递给一个变量中的函数,并且不知道程序运行之前数组的大小。在纸上的解决方案是有一个额外的元素到阵列,您将存储阵列的大小(我认为这被称为哨兵价值)。好的,但我在执行此操作时遇到问题。

传递array []作为函数参数似乎不起作用。我想我可以发送一个指向第一个元素的指针,但是如何访问数组的其余部分?

解决方案

在C语言中,数组在大多数情况下衰减为指向其第一个元素的指针:


6.3.2.1左值,数组和函数指示符



[...]除操作数 sizeof 运算符, _Alignof 运算符或
一元 & 运算符,或者是用于初始化数组的字符串字面值,将具有
类型>'数组类型''的表达式转换为类型为' '指向类型''的指针指向数组对象的初始元素
,并且不是左值。如果数组对象具有
寄存器存储类,则行为是未定义的。


这很有用,因为数组索引 a [i] ,使用指针运算来定义: *(a + i)

So ,您可以对指针使用与数组相同的操作。

仍然存在这种一致性的一个缺点:无法将数组传递到 struct



接下来, sentinel 是使用的元素类型的无效值作为停止标记,就像字符串0和指针大多是 NULL

实际上描述的是一个计数数组,它的长度预置为index ((size_t *)a)[ - 1] 或者其他的。

In C, I have to pass an array to a function in a single variable, and without knowing what the size the array will be before the program runs. The on-paper solution is to have an extra element to the array where you'll store the array's size (I think this is called a "sentinel value"). Ok, but I'm having problems implementing this.

Passing array[] as a function argument doesn't seem to work. I suppose I can send a pointer to the first element, but how do I then access the rest of the array?

解决方案

In C, an array decays to a pointer to its first element in most contexts:

6.3.2.1 Lvalues, arrays, and function designators

[...] Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

That is useful, because array indexing a[i], is defined using pointer arithmetic: *(a+i).
So, you can use the same operations on the pointer as on the array.
Still, there is one downside to this consistency: You cannot pass an array by value without wrapping it in a struct.

Next, a sentinel is an invalid value of the element type used as a stop marker, like for strings the 0 and for pointers mostly NULL.
What you actually described was a counted array, having the length prepended at index ((size_t*)a)[-1] or some such.

这篇关于C将未知大小的数组传递给单个变量中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆