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

ฟังก์ชัน strdup() และ strndup() ใน C/C++


ฟังก์ชัน strdup()

ฟังก์ชัน strdup() ใช้สำหรับทำซ้ำสตริง (duplicate a string) ฟังก์ชันนี้คืนค่าเป็นพอยน์เตอร์ที่ชี้ไปยังสตริงใหม่ที่ลงท้ายด้วย null character

ไวยากรณ์

char *strdup(const char *string);

ตัวอย่างการใช้งาน strdup()

#include <stdio.h>
#include <string.h>

int main() {
    char *str = "Helloworld";
    char *result;
    
    result = strdup(str);
    printf("The string : %s", result);
    
    return 0;
}

ผลลัพธ์

The string : Helloworld

ฟังก์ชัน strndup()

ฟังก์ชัน strndup() ทำงานคล้ายกับ strdup() แต่แตกต่างกันที่จะทำซ้ำสตริงได้เพียงจำนวนไบต์ที่กำหนดเท่านั้น (สูงสุด size ไบต์) ฟังก์ชันนี้ก็คืนค่าเป็นพอยน์เตอร์ชี้ไปยังสตริงใหม่ที่ลงท้ายด้วย null character เช่นกัน

ไวยากรณ์

char *strndup(const char *string, size_t size);

ตัวอย่างการใช้งาน strndup()

#include <stdio.h>
#include <string.h>

int main() {
    char *str = "Helloworld";
    char *result;
    
    result = strndup(str, 3);  // คัดลอกแค่ 3 ตัวอักษรแรก
    printf("The string : %s", result);
    
    return 0;
}

ผลลัพธ์

The string : Hel

หมายเหตุ: ทั้งสองฟังก์ชันจองหน่วยความจำแบบไดนามิกสำหรับสตริงใหม่ โปรแกรมเมอร์ต้องใช้ free() เพื่อปล่อยหน่วยความจำเมื่อไม่ใช้งานแล้ว เพื่อป้องกัน memory leak