Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ความแตกต่างระหว่าง pointer และ array ใน C


รายละเอียดเกี่ยวกับ pointer และ array ที่แสดงความต่าง:

Pointer

Pointer คือ variable ที่เก็บ address ของ variable อื่น เมื่อจัดสรร memory ให้ variable pointer จะชี้ไปที่ memory address ของ variable ใช้ unary operator ( * ) ประกาศ pointer variable

Syntax ของ pointer declaration:

datatype *variable_name;

datatype คือ data type เช่น int, char, float variable_name คือชื่อที่ผู้ใช้ตั้ง

โปรแกรมสาธิต pointers:

ตัวอย่าง

#include <stdio.h> int main () {    int a = 8;    int *ptr;    ptr = &a;    printf("Value of variable a: %d\n", a);    printf("Address of variable a: %d\n", ptr);    return 0; }

The output of the above program is as follows.

Value of variable a: 8 Address of variable a: -2018153420

Array

Array คือ collection ของ elements ชนิดเดียวกันใน contiguous memory locations Lowest address ตรง first element highest address ตรง last element Array index เริ่ม 0 จบ size - 1

Output

Syntax ของ array:

type array_name[array_size ];

array_name คือชื่อ array array_size คือขนาด

โปรแกรมสาธิต arrays:

ตัวอย่าง

#include <stdio.h> int main () {    int a[5];    int i,j;    for (i = 0;i<5;i++) {       a[i] = i+100;    }    for (j = 0;j<5;j++) {       printf("Element[%d] = %d\n", j, a[j] );    }    return 0; }

ผลลัพธ์

The output of the above program is as follows.

Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104