[英]How can I understand this code defined in C program?
我在 C 程序中定義了 3 個數組 A1、A2、A3,大小分別為 1500、980、980。 A1 由按升序排列的元素索引初始化,A2 - 也由索引初始化,但按降序排列。 在 A1 和 A2 初始化之后,執行以下操作:
int* A3 = malloc(sizeof(int) * SZ_A3);
memcpy(A3, A1, sizeof(int) * SZ_A3);
memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));
printf("%i", *(A3 + (SZ_A3 / 2)));
SZ_A#的定義如下:
#define SZ_A1 1500
#define SZ_A2 980
#define SZ_A3 980
哪個值將出現在標准輸出流中?
答案:979
我想知道為什么答案是 979。我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SZ_A1 1500
#define SZ_A2 980
#define SZ_A3 980
int main(void) {
int i, A1[SZ_A1], A2[SZ_A2];
// inicializo el array A1 en orden ascendente por sus indices. from i = 0 to i = SZ_A1-1
for (i = 0; i < SZ_A1; i++)
A1[i] = i;
// inicializo el array A2 en orden descendente por sus indices. from i = SZ_A2-1 to i = 0
for (i = SZ_A2 - 1; i >= 0; i--)
A2[i] = i;
int* A3 = malloc(sizeof(int) * SZ_A3);
memcpy(A3, A1, sizeof(int) * SZ_A3);
memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));
printf("%i", *(A3 + (SZ_A3 / 2)));
return 0;
}
我不明白這些行
memcpy(A3, A1, sizeof(int) * SZ_A3)
A3的價值是多少? 用memcpy, sizeof(int) * SZ_A3
個字節被復制,然后從內存區A1到內存區A3?。
memcpy(A3 + SZ_A3 / 2 + 1, A2, sizeof(int) * (SZ_A3 / 2));
memcpy(A3, A1, sizeof(int) * SZ_A3)
將A1
的前 980 個元素復制到A3
。 所以A3
現在包含最多979
序列號。
memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));
A3 + SZ_A3 / 2
是A3
中間元素的地址,即&A3[SZ_3 / 2]
,即&A3[490]
。 所以這將A2
的前 490 個元素復制到A3
后半部分。
所以A3
現在在索引0
到489
包含從0
序列號,然后從索引490
到979
重復它們。
最后,它打印*(A3 + (SZ_A3 / 2))
。 這將打印A3[490]
,即0
。
您還沒有按索引的降序初始化array A2
,您可以像這樣輕松地進行初始化:
A2[i] = SZ_A2-i-1;
即A2[0] = 979, A2[1] = 978, A2[2] = 977, ... , A2[978] = 1, A2[979] = 0
希望這能幫助您更好地理解代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.