使用typedef和array时,c中的const问题

Rob*_*ert 5 c typedef const

我有以下代码:

typedef float vec3_t[3];

void f(const vec3_t v[2]){
    // do stuff
}

int main(int argc, char * argv[]){
    vec3_t v[2];
    v[2][1] = 1;
    f(v);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它不会使用编译

gcc main.c -std=gnu99 -O0 -o main
Run Code Online (Sandbox Code Playgroud)

但是给出错误

main.c: In function ‘main’:'
main.c:293:5: warning: passing argument 1 of ‘f’ from incompatible pointer type [enabled by default]
     f(v);
     ^
main.c:286:6: note: expected ‘const float (*)[3]’ but argument is of type ‘float (*)[3]’
 void f(const vec3_t v[2]){
      ^
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我删除函数f中的const要求.这一切都运作良好.我无法弄清楚出了什么问题?

小智 0

为什么不将参数转换为 const?

typedef float vec3_t[3];

void f(const vec3_t v[2]){
    // do stuff
}

int main(int argc, char * argv[]){
    vec3_t v[2];
    v[2][1] = 1;
    f((const vec3_t*)v);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 寻求演员阵容并不是一个好主意。编译器抱怨是有原因的。除非您比编译器了解更多,否则简单的强制转换迟早可能会带来麻烦。 (2认同)