理解函数指针用C [英] Understanding functions and pointers in C

查看:104
本文介绍了理解函数指针用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很简单的问题,但到底是什么下面的函数原型是什么意思?

This is a very simple question but what does the following function prototype mean?

INT广场(INT Y,为size_t * X)

int square( int y, size_t* x )

什么贮藏为size_t *是什么意思?我知道为size_t是一种数据类型(INT> = 0)。但我怎么看*连接到它?它是一个指向x的内存位置?总的来说,我有这个东西的麻烦,如果有人可以提供一个方便的参考,我AP preciate它。

what dose the size_t* mean? I know size_t is a data type (int >=0). But how do I read the * attached to it? Is it a pointer to the memory location for x? In general I'm having trouble with this stuff, and if anybody could provide a handy reference, I'd appreciate it.

谢谢大家。我明白了一个指针是什么,但我想我有一个很难很难理解指针和功能之间的关系。当我看到定义为函数原型int平方米(INT X,int y)对,那么它是完全清楚,我是怎么回事。然而,当我看到类似 INT平方米(INT X,INT * Y),那么我不能 - 我的生活 - 明白的第二个参数的真正含义。在一定程度上我理解的意思是传递指针,但我不明白的东西不够好,操纵它在我自己的。

Thanks everybody. I understand what a pointer is, but I guess I have a hard hard time understanding the relationship between pointers and functions. When I see a function prototype defined as int sq(int x, int y), then it is perfectly clear to me what is going on. However, when I see something like int sq( int x, int* y), then I cannot--for the life of me--understand what the second parameter really means. On some level I understand it means "passing a pointer" but I don't understand things well enough to manipulate it on my own.

推荐答案

如何在理解教程指针

在然而这种情况下,指针是可能用于修改/返回值。在C语言中,也有一个功能可以返回一个值(请原谅哑例子)两个基本机制:

In this case however, the pointer is probably used to modify/return the value. In C, there are two basic mechanisms in which a function can return a value (please forgive the dumb example):

它可以直接返回值:

float square_root( float x )
{
    if ( x >= 0 )
        return sqrt( x );
    return 0;
}

或者,它可以通过返回一个指针:

Or it can return by a pointer:

int square_root( float x, float* result )
{
    if ( x >= 0 )
    {
        *result = sqrt( result );
        return 1;
    }
    return 0;
}

第一个被称为:

float a = square_root( 12.0 );

...而后者

float b;
square_root( 12.00, &b );

请注意,后者的例子还可以让你检查值是否返回是真实的 - 这种机制被广泛应用于C库,其中一个函数的返回值通常表示成功(或缺乏),而值本身是通过参数返回。

Note that the latter example will also allow you to check whether the value returned was real -- this mechanism is widely used in C libraries, where the return value of a function usually denotes success (or the lack of it) while the values themselves are returned via parameters.

因此​​,与后者你可以写:

Hence with the latter you could write:

float sqresult;
if ( !square_root( myvar, &sqresult ) )
{
   // signal error
}  
else
{ 
   // value is good, continue using sqresult!
}

这篇关于理解函数指针用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆