English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا الدرس، ستتعلم العلاقة بين النوع والمرجع في برمجة C. ستعلم أيضًا كيفية الوصول إلى عناصر النوع باستخدام المرجع.
قبل أن تفهم العلاقة بين النوع والمرجع، تأكد من التحقق من الموضوعين التاليين:
النوع هو مجموعة بيانات مرتبة. دعنا نكتب برنامجًا لطباعة عناوين عناصر النوع.
#include <stdio.h> int main() { int x[4]; int i; for(i = 0; i < 4; ++i) { printf("&x[%d] = %p\n", i, &x[i]); } printf("عنوان array x: %p", x); return 0; }
Output result
&x[0] = 1450734448 &x[1] = 1450734452 &x[2] = 1450734456 &x[3] = 1450734460 Address of x array: 1450734448
The difference between two consecutive elements of array x is 4 bytes. This is because the size of int is 4 bytes (in our compiler).
Please note that the address &x[0] and x are the same. This is because the variable name x points to the first element of the array.
From the above examples, it can be clearly seen that &x[0] is equivalent to x, and x[0] is equivalent to *x.
Similarly,
&x[1] 等同于 x+1 和 x[1] 等同于 *(x+1).
&x[2] 等同于 x+2 和 x[2] 等同于 *(x+2).
...
基本上 &x[i] 等同于 x+i 和 x[i] 等同于 *(x+i).
#include <stdio.h> int main() { int i, x[6], sum = 0; printf("Enter 6 numbers: "); for(i = 0; i < 6; ++i) { // Equivalent to scanf("%d", &x[i]); scanf("%d", x+i); // Equivalent to sum += x[i] sum += *(x+i); } printf("Total = %d", sum); return 0; }
When running this program, the output is:
Enter 6 numbers: 2 3 4 4 12 4 Total = 29
In this example, we declare an array x with 6 elements. To access the elements of the array, we use a pointer.
In most cases, the array name decays to a pointer. In short, the array name is converted to a pointer. This is why you can use pointers to access array elements. However, you should remember thatPointers and arrays are not the same.
In some cases, the array name does not decay to a pointer.
#include <stdio.h> int main() { int x[5] = {1, 2, 3, 4, 5}; int* ptr; // ptr was assigned the address of the third element ptr = &x[2]; printf("*ptr = %d \n", *ptr); // 3 printf("*(ptr+1) = %d \n", *(ptr+1)); // 4 printf("*(ptr-1) = %d", *(ptr-1)); // 2 return 0; }
When running this program, the output is:
*ptr = 3 * (ptr+1) = 4 * (ptr-1) = 2
في هذا المثال، يتم تخصيص عنوان الثالث من الصف x [2] إلى مرجع ptr. لذلك، عند طباعة *ptr، يتم عرض 3.
ومن ثم، يتم الحصول على الرابع عن طريق إدراج (ptr+1). بنفس الطريقة، يتم الحصول على الثاني عن طريق إدراج (ptr-1).