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

Array of Pointers to Strings ใน C: พิมพ์ค่าและ Address

Array of pointers to strings = อาร์เรย์ที่แต่ละ element เป็น pointer ชี้ไปยัง string

การประกาศ

char *a[] = {"one", "two", "three"};
// a[0] ชี้ "one", a[1] ชี้ "two", ...

ข้อดี

  • ไม่ต้องกำหนดขนาดคงที่สำหรับแต่ละ string (ประหยัด memory)
  • string แต่ละตัวใช้พื้นที่เท่าที่จำเป็น

โปรแกรมที่ 1: พิมพ์ค่าและ Address

#include <stdio.h>
#include <string.h>
void main() {
    int i;
    char *a[5] = {"One", "Two", "Three", "Four", "Five"};
    printf("Values:\n");
    for (i = 0; i < 5; i++)
        printf("%s\n", a[i]);
    printf("Addresses:\n");
    for (i = 0; i < 5; i++)
        printf("%p\n", (void*)a[i]);
}

ผลลัพธ์

Values:
One
Two
Three
Four
Five
Addresses:
0x... (addresses จะต่างกันทุกครั้งที่รัน)

โปรแกรมที่ 2: ใช้ pointer เดินผ่าน string

#include <stdio.h>
#include <string.h>
void main() {
    char string[20] = "TutorialPoint";
    char *pointer = string;
    printf("The string is: ");
    while (*pointer != '\0') {
        printf("%c", *pointer);
        pointer++;
    }
}

ผลลัพธ์

The string is: TutorialPoint