原型变长数组 [英] Prototype for variable-length arrays
问题描述
我想编写一个函数,它接受一个可变大小的数组在C。
I am trying to write a function that takes an array of an variable size in c.
void sort(int s, int e, int arr[*]){
...
}
它说,对可变长度数组,它需要在函数声明有界。这意味着什么?我用x code 4.0,与LLVM编译器2.0。
It says that for variable length arrays, it needs to be bounded in the function declaration. What does that mean? I am using xcode 4.0, with the LLVM compiler 2.0.
感谢您的帮助。
推荐答案
如果你不使用的C99变长数组,通常的解决方法是在一个指针传递到第一个元素,任何你想要的索引沿用来访问的元素。
If you're not using the C99 variable length arrays, the usual solution is to pass in a pointer to the first element, along with any indexes you want to use for accessing the elements.
下面是一张code的打印出一系列的数组,类似于你想与做你的排序
。
Here's a piece of code that prints out a range of an array, similar to what you're trying to do with your sort
.
#include <stdio.h>
static void fn (int *arr, size_t start, size_t end) {
size_t idx;
for (idx = start; idx <= end; idx++) {
printf ("%d ", arr[idx]);
}
putchar ('\n');
}
int main (void) {
int my_array[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
fn (my_array, 4, 6);
return 0;
}
这个输出要素四至六,包容性(从零开始),赠送:
This outputs elements four through six inclusive (zero-based), giving:
5 4 3
有几点要注意。
-
使用
my_array
在函数调用FN
自动衰变的数组指针它的第一个元素。这实际上在大多数(不是全部)情况发生在你使用数组,所以你不必明确说明&放大器;(my_array [0])
Using
my_array
in that function call tofn
automatically "decays" the array into a pointer to its first element. This actually happens under most (not all) circumstances when you use arrays, so you don't have to explicitly state&(my_array[0])
.
C处已经的的的一个很好的排序功能内置于标准库,名为的qsort
。在许多情况下,这是你应该使用什么(除非要么你有一个特定的算法要用于排序,或者你正在做的一门功课/自我教育运动)。
C already has a very good sort function built in to the standard library, called qsort
. In many cases, that's what you should be using (unless either you have a specific algorithm you want to use for sorting, or you're doing a homework/self-education exercise).
这篇关于原型变长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!