Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Passing arrays in C: square brackets vs. pointer

I'm wanting to pass an array into a function. From what I can see, there are 2 ways of doing this:

1.

void f (int array[]) {
    // Taking an array with square brackets
}

2.

void f (int *array) {
    // Taking a pointer
}

Each one is called by:

int array[] = {0, 1, 2, 3, 4, 5};
f (array);

Is there any actual difference between these 2 approaches?

question from:https://stackoverflow.com/questions/65890496/passing-around-array-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your specific example there is no difference.

In more general case one difference between these two approaches stems from the fact that in case of [] syntax the language performs "usual" checks for correctness of array declaration. For example, when the [] syntax is used, the array element type must be complete. There's no such requirement for pointer syntax

struct S;
void foo(struct S *a); // OK
void bar(struct S a[]); // ERROR

A specific side-effect of this rule is that you canon declare void * parameters as void [] parameters.

And if you specify array size, it has to be positive (even though it is ignored afterwards).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...