#include<stdio.h>
int main(){
int a[] = {1,2,3};
int b[] = {4,5,6};
b = a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果出现这个错误:
array type 'int [3]' is not assignable
Run Code Online (Sandbox Code Playgroud)
我知道数组是左值并且不可分配,但在这种情况下,编译器所要做的就是重新分配指针。b
应该只指向 的地址a
。为什么这不可行?
#include <stdio.h>
int a[] = {1,2};
void test(int in[3]){
//
}
int main() {
test(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码int in[3]
中与int *in
. 这个数字3
并没有真正做任何事情,它甚至不是正确的大小,但即便如此,编译器也不会抱怨。那么这个语法在 C 中被接受还是我缺少一个功能是有原因的吗?
#include <iostream>
typedef enum my_time {
day,
night
} my_time;
int main(){
// my_time t1 = 1; <-- will not compile
int t2 = night;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,如何期望我可以enum
为 an 赋值int
,但不能以其他方式赋值?
当然,这一切都可以在C
.
假设这段代码:
#include <iostream>
struct test {
int a[3];
float b[2];
};
Run Code Online (Sandbox Code Playgroud)
我可以通过以下两种方式初始化数组:
int main(){
test t = {{1,2,3}, {1.0,2.0}};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者
int main(){
test t = {1, 2, 3, 1.0, 2.0};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二种方法是如何编译的?编译器是否选择每个值并按顺序放入数组槽?
#include <stdio.h>
void test2(int (&some_array)[3]){
// passing a specific sized array by reference? with 3 pointers?
}
void test3(int (*some_array)[3]){
// is this passing an array of pointers?
}
void test1(int (some_array)[3]){
// I guess this is the same as `void test1(some_array){}`, 3 is pointless.
}
int main(){
//
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以上3种语法有什么区别?我在每个部分都添加了评论,以使我的问题更加具体。