9

サンプルプログラムは次のとおりです。

#include <stdio.h>

void foo(int b[]){
    printf("sizeof in foo: %i\n", sizeof b);
}

int main(){
    int a[4];
    printf("sizeof in main: %i\n", sizeof a);
    foo(a);
}

出力は次のとおりです。

sizeof in main: 16
sizeof in foo: 8

問題は、関数の境界で標準のポインターに変換されただけの場合、その構文のポイントは何ですか?

4

2 に答える 2

12
  1. It's syntactic sugar: void foo(int b[]) suggests that b is going to be used as an array (rather than a single out-parameter), even though it really is a pointer.

  2. It's a left-over from early versions of C, where postfix [] was the syntax for a pointer declaration.

于 2012-05-11T15:02:53.527 に答える
0

Question is, what's the point of that syntax if it's just converted to a standard pointer at the function boundary?

In this case, because you're passing the array as an argument C has created a pointer to a given address - however, the really interesting case is what happens when you allocate an array on the stack, and only use it there.

When you do this, the compiler then converts load statements for that array not into a pointer plus offset, but direct access to stack base + offset - since why not? It doesn't make sense to store the pointer anyway.

However, when it comes to passing that array around, the compiler passes the address of the base of the array to the function - as a pointer.

In short, [] helps you do pointer arithmetic more nicely. In the case of declaring arrays, it can be optimised away - which is why arrays are not pointers, although they are accessed via pointers in certain circumstances (and not in others).

于 2012-05-11T15:07:56.887 に答える