注册 登录
编程论坛 数据结构与算法

请问:指针程序出现这情况是什么原因,如何较好避免

natto 发布于 2016-04-10 19:01, 3389 次点击
请教一下:以下程序编译后,虽无错误,但出现如下的警告,英文意思百度了下,大约能看得懂是什么意思,但是不能理解,因为按书上所说,这样使用指针是可以,但是为什么会出现这种警告呢,又该怎么编写是相对比较正确的程序呢,请不吝指教,谢谢!
程序代码:
#include<stdio.h>
int add(int,int);
main()
{
    int x,y,z,*p,*q;
    printf("请输入一个数");
    scanf("%d %d",&x,&y);
    p=&x;q=&y;
    z=add(p,q);
    printf("%d\n",z);
}
int add(int *a,int *b)
{
    int sum;
    sum=*a+*b;
    return sum;
}

--------------------配置: vc6.0 - CUI Release, 编译器类型: Microsoft C++ Compiler--------------------


[Warning]  C4047: 'function' : 'int ' differs in levels of indirection from 'int *'
[Warning]  C4024: 'add' : different types for formal and actual parameter 1
[Warning]  C4047: 'function' : 'int ' differs in levels of indirection from 'int *'
[Warning]  C4024: 'add' : different types for formal and actual parameter 2
[Warning] C4028: formal parameter 1 different from declaration
[Warning]  C4028: formal parameter 2 different from declaration

完成编译 I:\electronic_practice\c_program\Console_Application_vc6\Console_Application_vc6.c: 0 个错误, 6 个警告
生成 I:\electronic_practice\c_program\Console_Application_vc6\vc6.0\Console_Application_vc6.obj
2 回复
#2
azzbcc2016-04-11 09:25
换个编译器吧

[09:24:08 azzbcc@XJH-PC src]$ gcc -O2 -W -Wall C.c -o C
C.c:3:1: warning: return type defaults to ‘int’ [-Wreturn-type]
 main()
 ^
C.c: In function ‘main’:
C.c:9:5: warning: passing argument 1 of ‘add’ makes integer from pointer without a cast [enabled by default]
     z=add(p,q);
     ^
C.c:2:5: note: expected ‘int’ but argument is of type ‘int *’
 int add(int,int);
     ^
C.c:9:5: warning: passing argument 2 of ‘add’ makes integer from pointer without a cast [enabled by default]
     z=add(p,q);
     ^
C.c:2:5: note: expected ‘int’ but argument is of type ‘int *’
 int add(int,int);
     ^
C.c: At top level:
C.c:12:5: error: conflicting types for ‘add’
 int add(int *a,int *b)
     ^
C.c:2:5: note: previous declaration of ‘add’ was here
 int add(int,int);
     ^
C.c: In function ‘main’:
C.c:7:10: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d %d",&x,&y);
          ^
C.c:11:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

#3
huzi7412016-04-12 12:37
1、函数申明尽量使用标准的;
2、函数没有返回值,尽量加上void;
#include<stdio.h>
int add(int *a,int *b);
void main()
{
    int x,y,z,*p,*q;
    printf("请输入一个数");
    scanf("%d %d",&x,&y);
    p=&x;q=&y;
    z=add(p,q);
    printf("%d\n",z);
}
int add(int *a,int *b)
{
    int sum;
    sum=*a+*b;
    return sum;
}
1