Dor*_*tan 3 c arrays struct pointers pass-by-value
在C:
当通过值(通过参数)将结构发送到函数时,会创建新的结构,因此更改函数内的结构将不会更改原始结构.
当数组通过值(通过参数)发送到函数时,会创建一个新指针,因此更改函数内的数组不会更改原始数组,而是更改函数内的数组值(因为我们有指向原始数组的指针)将更改原始数组中的值.
当带有数组字段的结构(通过参数)通过值发送到函数时,????? 是创建的,因此更改函数内的数组(指针)不会更改原始数组,更改数组值不会更改原始数组中的值.
第三点是否意味着结构的数组字段在被发送到函数时将被完全克隆?为什么不只是使用指针?规范对此有何规定?
我玩过的一段代码:
typedef struct {
int value;
int array[3]; /* initialized to 0 by default */
} Struct_t;
void foo(Struct_t structure)
{
printf("-- %p\n", structure.array); /* Pointer to local array */
structure.value = 1;
*structure.array = 1; /* Won't change the original array */
*(structure.array + 1) = 1; /* Won't change the original array */
structure.array[2] = 1; /* Won't change the original array */
}
int main()
{
Struct_t s = { .value = 0 };
foo(s);
printf("-- %p\n", s.array); /* Pointer to original array */
printf("%d\n", s.value);
printf("%d\n", s.array[0]);
printf("%d\n", s.array[1]);
printf("%d\n", s.array[2]);
}
Run Code Online (Sandbox Code Playgroud)
输出:
-- 0x7ffe8f17d194
-- 0x7ffe8f17d1b4
0
0
0
0
Run Code Online (Sandbox Code Playgroud)
OP的"发送数组时..."需要澄清.
当数组通过值(通过参数)发送到函数时,会创建一个新指针,因此更改函数内的数组不会更改原始数组,而是更改函数内的数组值(因为我们有指向原始数组的指针)将更改原始数组中的值.(OP)
当s[]传递一个数组(如下所示)strcpy(char *s1, const char *s2)时,首先进行转换.该对象s将转换为数组的第一个元素的地址. strcpy()不接收s[]作为s1参数,而是接收值的副本&s[0].
char s[6] = "Hello";
strcpy(s, "World");
Run Code Online (Sandbox Code Playgroud)
内strcpy(),s1不是一个数组. s1是指向a的指针char. strcpy()没有"更改函数内部的数组"的概念,因为函数不知道s1指向数组内存,分配的内存或其他任何东西. strcpy()了解s1点数char.
第三点是否意味着结构的数组字段在被发送到函数时将被完全克隆?
是.将对象传递给C中的函数时,它可能会被转换,然后按值传递.这很像任何任务.转换后的对象内容被复制到目标.它没有什么区别,转换之后,如果对象是一个struct, union, int, double, void*, int(*)()等或一个struct包含数组.
int a;
double b;
a = 5; // 5 is copied to a
b = a; // a is converted to double and copied to b
char s[6] = "Hello";
char *e;
void *v;
e = s; // s is converted to the address on the first array element and then copied to e
v = e; // e is converted to a `void*` and then copied to v
Struct_t f = {0};
Struct_t g;
g = f; // f is copied to g
Run Code Online (Sandbox Code Playgroud)