首页 > 解决方案 > 如何修复两个警告“警告:格式指定类型'char *'但参数的类型为'char (*)[256]' [-Wformat]”

问题描述

这是我已经尝试修复它很长一段时间的代码..它仍然拒绝工作我的朋友联系我,看看我是否可以帮助她使用她的代码(如下)如果有人能告诉我它有什么问题,非常感谢.

#include <stdio.h>

#include <math.h>

int main() {
//declarations
double originlat,originlong,deslat,deslong;
double rad1,rad2,rad3,rad4;
char originplace[256], desplace[256];
//input
printf("Enter origin latitude, longitude, and place.\n");
scanf("%lf %lf %[^\n]s",&originlat,&originlong,&originplace);
printf("You entered latitude %0.2lf, longitude %0.2lf, place \"%s\"\n\n", originlat,originlong,originplace);
printf("Enter destination latitude, longitude, and place.\n");
scanf("%lf %lf %[^\n]s",&deslat,&deslong,&desplace);
printf("You entered latitude %0.2lf, longitude %0.2lf, place \"%s\"\n\n",deslat,deslong,desplace);
printf("Origin: %s\n",originplace);
printf("\t%0.2lf degrees is %0.4lf radians (latitude)\n",originlat,rad1);
//process
rad1 = originlat/(180/M_PI);
//output
printf("\t%0.2lf degrees is %0.4lf radians (latitude)\n\n",originlong,rad2);
printf("Destination: %s\n",desplace);
printf("\t%0.2lf degrees is radians (latitude)\n",deslat);
printf("\t%0.2lf degrees is radians (latitude)\n\n",deslong);
printf("The distance from %s to %s is miles.",originplace,desplace);
///:END ToDo

return 0;
}

标签: carrayspointersscanfc-strings

解决方案


对于%[^\n]s,scanf应该传递一个指向 a 的指针char,它是可以写入读取字符char的数组中的第一个。对于该转换,代码具有参数。是一个 256 的数组,所以它的地址 ,是一个指向 256 的数组的指针。charscanf&originplaceoriginplacechar&originplacechar

与其传递originplace,不如传递其第一个元素的地址 ,&originplace[0]

为方便起见,您可以简单地编写originplace. 根据 C 的规则,这将自动转换为指向其第一个元素的指针。(无论何时在表达式中使用数组,它都会自动转换为指向其第一个元素的指针,除非它是 的操作sizeof数、一元的操作数&或用于初始化数组的字符串文字。)

另请注意rad1rad2在初始化之前打印。


推荐阅读