我正在尝试编译此代码。它给了我这个错误:
format specifies type 'char *' but the argument has type 'char **' [-Werror,-Wformat]
在我%s
的所有内容中。会是什么呢?这是一本书的例子。谢谢你的帮助。
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int response;
char *lName[20] = {0};
char *fName[20] = {0};
char *number[20] = {0};
FILE *pWrite;
FILE *pRead;
printf("\n\tPhone Book\n");
printf("\n1\tAdd phone book entry\n");
printf("2\tPrint phone book\n\n");
printf("Select an option: ");
scanf("%d", &response);
if ( response == 1 ) {
scanf("%s", fName);
printf("\nEnter last name: ");
scanf("%s", lName);
printf("\nEnter phone number: ");
scanf("%s", number);
pWrite = fopen("phone_book.dat", "a");
if ( pWrite != NULL ) {
fprintf(pWrite, "%s %s %s\n", fName, lName, number);
fclose(pWrite);
} else
goto ErrorHandler;
}
else if ( response == 2 ) {
pRead = fopen("phone_book.dat", "r");
if ( pRead != NULL ) {
printf("\nPhone Book Entries\n");
while ( !feof(pRead) ) {
fscanf(pRead, "%s %s %s", fName, lName, number);
if ( !feof(pRead) )
printf("\n%s %s\t%s", fName, lName, number);
}
printf("\n");
}
else
goto ErrorHandler;
}
else {
printf("\nInvalid selection\n");
}
exit(EXIT_SUCCESS);
ErrorHandler:
perror("The following error occurred");
exit(EXIT_FAILURE);
} //end main
答案 0 :(得分:1)
正如你可能猜到的,这里有些错误:
char *lName[20] = {0};
char *fName[20] = {0};
char *number[20] = {0};
你看,当你声明一个这样的数组时:
int a[20];
你对编译器说的是:“给我一个20个整数的数组,并使变量”a“指向它们的开头”。这就像说a
实际上是int*
,而不是int。所以,如果你宣布
int* a[20];
你宣称的是一系列“整数指针”。就像a
是int**
,也不是int。
将其应用于您的问题:
char lName[20] = {0};
char fName[20] = {0};
char number[20] = {0};
你看,现在它声明了3个字符数组,变量lName,fName和number将指向数组的开头并且类型为char*
,正如scanf
所期望的那样使用%s
。
答案 1 :(得分:0)
你的分配指针。
此
char *lName[20] = {0};
char *fName[20] = {0};
char *number[20] = {0};
应该是这个
char lName[20] = {0};
char fName[20] = {0};
char number[20] = {0};
答案 2 :(得分:0)
这可能是输入错误。
char *lName[20] = {0};
应该是
char lName[20] = {0};
应对fName
和number
的定义进行类似的更改。
答案 3 :(得分:0)
char *lName[Val] = {0};
char *fName[Val] = {0};
char *number[Val] = {0};
相当于二维数组。但是你将它用作一维数组。只需执行以下操作
char lName[20] = {0};
char fName[20] = {0};
char number[20] = {0};
它会解决你的问题。