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

การส่งสมาชิก Array แยกต่างหากเป็น Argument ให้ Function ใน C

การส่ง สมาชิกเฉพาะตัวของ Array** ให้ฟังก์ชัน คือการส่งค่าของ Element ที่ Index เฉพาะ (Pass by Value สำหรับแต่ละ Element)

หลักการ

  • ใน Function Call: ส่ง arr[index] (ค่าของสมาชิก)
  • ใน Function Parameter: รับเป็นตัวแปรธรรมดา void func(int val)

ตัวอย่างที่ 1: ส่ง Element แรกและสุดท้าย

#include <stdio.h>

void display(int first, int last) {
    printf("First element = %d\n", first);
    printf("Last element = %d\n", last);
}

int main() {
    int a[5], i;
    
    printf("Enter 5 elements: ");
    for(i = 0; i < 5; i++)
        scanf("%d", &a[i]);
    
    display(a[0], a[4]);  // ส่งค่าสมาชิก index 0 และ 4
    
    return 0;
}

ผลลัพธ์

Enter 5 elements: 10 20 30 40 50
First element = 10
Last element = 50

ตัวอย่างที่ 2: ส่ง Element ที่ 1 และ 6

#include <stdio.h>

void arguments(int first, int sixth) {
    printf("First element = %d\n", first);
    printf("Sixth element = %d\n", sixth);
}

int main() {
    int a[10], i;
    
    printf("Enter 6 elements: ");
    for(i = 0; i < 6; i++)
        scanf("%d", &a[i]);
    
    arguments(a[0], a[5]);  // Index 0 และ 5 (Element ที่ 1 และ 6)
    
    return 0;
}

ผลลัพธ์

Enter 6 elements: 1 2 3 4 5 6
First element = 1
Last element = 6

ข้อสังเกตสำคัญ

  1. Pass by Value - ฟังก์ชันได้รับ Copy ของค่า ไม่สามารถแก้ไข Array ต้นฉบับได้
  2. เหมาะกับ - ส่งค่าเพื่ออ่าน/คำนวณ ไม่ต้องแก้ไข
  3. ไม่เหมาะกับ - ต้องการแก้ไขค่าใน Array, หรือส่งหลาย Element (โค้ดยาว)

เปรียบเทียบวิธีส่ง Array ให้ Function

วิธีSyntaxสามารถแก้ไข Array ได้?เหมาะสำหรับ
ส่ง Element เดี่ยวfunc(arr[i])ไม่ได้ (Pass by Value)อ่านค่าเฉพาะตัว
ส่งหลาย Elementfunc(arr[0], arr[1], ...)ไม่ได้อ่านค่าหลายตัว แต่อย่างน้อย
ส่ง Array ทั้งอันfunc(arr)ได้ (Pass by Reference)ประมวลผลทั้ง Array, ต้องแก้ไข
ส่ง Pointer + Sizefunc(arr, n)ได้ยืดหยุ่น กำหนด Size เองได้

ตัวอย่างเพิ่มเติม: คำนวณค่าเฉลี่ย 3 คะแนน

#include <stdio.h>

float average(int a, int b, int c) {
    return (a + b + c) / 3.0f;
}

int main() {
    int scores[3];
    printf("Enter 3 scores: ");
    scanf("%d %d %d", &scores[0], &scores[1], &scores[2]);
    
    printf("Average: %.2f\n", average(scores[0], scores[1], scores[2]));
    return 0;
}