int main(int argc, const char * argv[])
{
int age = 40;
float gpa = 3.25f;
char grade ='A';
double fun = 2.000043f;
char companyName[20] = "O'Brien Enterprises";
int *pAge = &age;
int *pGpa = &gpa;
int *pGrade = &grade;
int *pFun = &fun;
int *pCompanyName = &companyName;
printf("Value of variables through pointers:\n");
printf("age = %i\n", *pAge);
printf("gpa = %f\n",*pGpa);
printf("grade = %c\n", *pGrade);
printf("fun = %d\n", *pFun);
printf("companyName = %s\n", *pCompanyName);
return 0;
}
当我运行此代码时,Xcode会回复大量警告和错误。在声明和初始化除age
之外的所有变量的指针时,它会显示incompatible pointer types
。在尝试打印出来时,除了age
,format specifies a different type
以外的所有内容都会显示。为什么是这样?当代码按原样运行时,我得到以下结果:
Value of variables through pointers:
age = 40
gpa = 0.000000
grade = A
fun = -2147483648
(lldb)
答案 0 :(得分:5)
您已将所有这些声明为整数的指针,而它们应该是指向int
,float
,char
的指针,等等!
int *pAge = &age;
float *pGpa = &gpa;
char *pGrade = &grade;
double *pFun = &fun;
char **pCompanyName = &companyName;
答案 1 :(得分:0)
这是正确的代码
#include <stdio.h>
int main(void)
{
int age = 40;
float gpa = 3.25f;
char grade ='A';
double fun = 2.000043f;
char companyName[20] = "O'Brien Enterprises";
int *pAge = &age;
float *pGpa = &gpa;
char *pGrade = &grade;
double *pFun = &fun;
char *pCompanyName = companyName;
printf("Value of variables through pointers:\n");
printf("age = %i\n", *pAge);
printf("gpa = %f\n",*pGpa);
printf("grade = %c\n", *pGrade);
printf("fun = %f\n", *pFun);
printf("companyName = %s\n", pCompanyName );
return 0;
}
输出
Value of variables through pointers:
age = 40
gpa = 3.250000
grade = A
fun = 2.000043
companyName = O'Brien Enterprises
您必须在printf函数中使用corect指针类型和格式说明符。
或者,如果您想要一个指向字符数组的指针,那么您可以编写
char ( *pCompanyName )[20] = &companyName;
并相应地
printf("companyName = %s\n", *pCompanyName );