| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 3550 人关注过本帖
标题:函数参数为指针,但实际传入值类型为什么不会报错?
取消只看楼主 加入收藏
Ted_Ming
Rank: 2
等 级:论坛游民
帖 子:15
专家分:35
注 册:2016-11-2
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:2 
函数参数为指针,但实际传入值类型为什么不会报错?
问题:
1、C 为什么不严格检查参数类型
2、为什么 参数是 int [] 传入 int 是警告,而 double [] 传入 double 是报错
#include <stdio.h>
int a(int []);                                                                                                                                                                                         

int main(void)
{
   int b = 10;
   int s = a(b);

   printf("%d\n", s);
   return 0;
}

int a(int s[])
{
   return s;  
}

// 编译器警告如下
test.c:7:14: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'int *'; take the address with & [-Wint-conversion]
   int s = a(b);
             ^
             &
test.c:2:11: note: passing argument to parameter here
int a(int []);
          ^
test.c:15:11: warning: incompatible pointer to integer conversion returning 'int *' from a function with result type 'int'; dereference with * [-Wint-conversion]
   return s;
          ^
          *
2 warnings generated.


// 结果输出
10

//----------------
#include <stdio.h>
int a(double []);

int main(void)
{
   double b = 10;
   int s = a(b);

   printf("%d\n", s);
   return 0;
}

int a(double s[])
{                                                                                                                                                                                                           
   return s;
}

// 编译器报错
test.c:7:14: error: passing 'double' to parameter of incompatible type 'double *'; take the address with &
   int s = a(b);
             ^
             &
test.c:2:14: note: passing argument to parameter here
int a(double []);
             ^
test.c:15:11: warning: incompatible pointer to integer conversion returning 'double *' from a function with result type 'int' [-Wint-conversion]
   return s;
搜索更多相关主题的帖子: include double return 编译器 
2016-12-31 22:41
Ted_Ming
Rank: 2
等 级:论坛游民
帖 子:15
专家分:35
注 册:2016-11-2
收藏
得分:0 
回复 2楼 九转星河
不匹配,但是只是警告,没有报错啊,那为什么double 类型报错了呢。是不是参数如果是指针,就只检查他的值是不是整数,毕竟指针的值(即地址)就是整数?
2016-12-31 22:49
Ted_Ming
Rank: 2
等 级:论坛游民
帖 子:15
专家分:35
注 册:2016-11-2
收藏
得分:0 
测试如下:
1、 a(int []); int b = 10;
    -- a(b); // 警告
    -- a(&b); // 正常
2、 a(double []); double b = 10;
    -- a(b); // 报错
    -- a(&b); // 正常
是不是在传入当参数为指针的时候,编译器其实只是检查了指针的值(地址)是否为整数呢
2016-12-31 22:54
快速回复:函数参数为指针,但实际传入值类型为什么不会报错?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012134 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved