Devdit
 

format %d expects argument of type int *, but argument 2 has type int คือ วิธีแก้ไข

1.1K

เขียนโปรแกรมภาษา C รับค่าตัวเลขชนิด int จากผู้ใช้งานด้วยคำสั่ง scanf แต่รันแล้วขึ้นข้อความว่า warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ แบบนี้ต้องแก้ไขอย่างไร

#include <stdio.h>

int main()
{
    int i = 0;
    printf("Please input : ");
    scanf("%d", i);
    return 0;
}

 

วิธีแก้ไข

ปัญหานี้เกิดจากตัวแปร i ตรงคำสั่ง scanf นั้นต้องใส่ & ไว้หน้าตัวแปรเสมอ เป็น scanf("%d", &i) ซึ่งรวมไปถึงการรับค่าตัวแปรชนิดอื่นๆ ของภาษา C ด้วยคำสั่ง scanf ด้วย สามารถแก้ไขโค้ดได้ดังนี้

#include <stdio.h>

int main()
{
    int i = 0;
    printf("Please input : ");
    scanf("%d", &i);
    return 0;
}
เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ