C 无符号整数*代替整数
我声明并定义一个函数如下:C 无符号整数*代替整数,c,function,pointers,C,Function,Pointers,我声明并定义一个函数如下: unsigned int doSomething(unsigned int *x, int y) { if(1) //works if(y) //reports the error given below //I use any one of the ifs above, and not both at a time return ((*x) + y); //works fine when if(1) is used, not ot
unsigned int doSomething(unsigned int *x, int y)
{
if(1) //works
if(y) //reports the error given below
//I use any one of the ifs above, and not both at a time
return ((*x) + y); //works fine when if(1) is used, not otherwise
}
unsigned int x = 10;
doSomething(&x, 1);
passing argument 1 of 'doSomething' makes pointer from integer without a cast [enabled by default]|
note: expected 'unsigned int *' but argument is of type 'int'|
我从main()调用函数,如下所示:
unsigned int doSomething(unsigned int *x, int y)
{
if(1) //works
if(y) //reports the error given below
//I use any one of the ifs above, and not both at a time
return ((*x) + y); //works fine when if(1) is used, not otherwise
}
unsigned int x = 10;
doSomething(&x, 1);
passing argument 1 of 'doSomething' makes pointer from integer without a cast [enabled by default]|
note: expected 'unsigned int *' but argument is of type 'int'|
编译器报告错误和警告,如下所示:
unsigned int doSomething(unsigned int *x, int y)
{
if(1) //works
if(y) //reports the error given below
//I use any one of the ifs above, and not both at a time
return ((*x) + y); //works fine when if(1) is used, not otherwise
}
unsigned int x = 10;
doSomething(&x, 1);
passing argument 1 of 'doSomething' makes pointer from integer without a cast [enabled by default]|
note: expected 'unsigned int *' but argument is of type 'int'|
我尝试对函数返回类型、函数调用以及参数类型使用所有可能的组合。我错在哪里
完整代码:
unsigned int addTwo(unsigned int *x, int y)
{
if(y)
return ((*x) + y);
}
int main()
{
unsigned int operand = 10;
printf("%u", addTwo(&operand, 1));
return 0;
}
尝试在main()中显式声明它
如果声明不正确,编译器会假定默认情况下返回int我也在Windows上使用了GCC4.4.3。
此程序成功编译并生成输出“11”:
#包括
无符号整数doSomething(无符号整数*x,整数y);
int main()
{
无符号整数res=0;
无符号整数x=10;
res=剂量测定法(&x,1);
printf(“结果:%d\n”,res);
返回0;
}
无符号整数doSomething(无符号整数*x,整数y)
{
如果(y)
{
printf(“y正常\n”);
}
如果(1)
{
printf(“1正常\n”);
}
返回((*x)+y);
}
请检查这是否适用于您,然后将其与您的程序进行比较。确保正确声明了函数。您返回的是添加到
int
(y)中的无符号int
(x),可以是有符号的int
。在不强制转换第二个操作数(y)的情况下,如果您打算在此函数中仅返回无符号int
,这可能会导致未定义的行为。在启用所有警告的情况下在我的Mac(GCC 4.6.3)上编译良好(除了控制到达非无效函数的末尾
)。您能否发布一个完整的示例,说明您何时实际收到警告(未与不会导致警告的代码混合)?包括如何启动gcc?您确定这就是调用doSomething
函数的方式吗?该错误表明您正在传递一个int
作为第一个参数。可能是您当时使用的代码有问题。你能把全部代码都贴出来吗?或者是一篇给出警告的可编译文章?有了“完整代码”,我没有得到帖子中提到的警告(MingW gcc 4.6.2,gcc-pedantic-Wall
(我得到了其他警告:你需要#包括,如果条件为false,你需要在addTwo()的末尾返回一些东西)但除此之外,代码编译并执行fineOP程序在我的mingw3.2中编译成功。x
声明为unsigned int
。当int
添加到unsigned int
时,int
转换为unsigned int
,然后作为我们的一部分进行添加算术转换。行为是完全定义的[所涉及类型的确切大小和表示除外]。