【问题标题】:C function prototype: \\char *strinv(const char *s);C函数原型:\\char *strinv(const char *s);
【发布时间】:2020-04-19 09:23:14
【问题描述】:
char *strinv(const char *s); //that's the given prototype

我对 *strinv 部分有点不安全。这是否意味着该函数在调用时会自动取消引用?还是把函数定义为指针?

提前感谢您的澄清。

【问题讨论】:

  • 表示返回类型为char *
  • Does it mean that the function is automatically dereferenced when called? - 你能详细说明你的意思吗?

标签: c prototype c-strings dereference function-declaration


【解决方案1】:

这个函数声明

char * strinv(const char *s);

声明一个返回类型为char * 的函数。例如,该函数可以为字符串动态分配内存并返回指向该字符串的指针。

这是一个演示程序,展示了如何定义函数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * strinv(const char *s)
{
    size_t n = strlen( s );

    char *t = malloc( n + 1 );

    if ( t != NULL )
    {
        size_t i = 0;

        for ( ; i != n; i++ ) t[i] = s[n-i-1];

        t[i] = '\0';
    }

    return t;
}

int main(void) 
{
    const char *s = "Hello Worlds!";

    char *t = strinv( s );

    puts( t );

    free( t );

    return 0;
}

程序输出是

!sdlroW olleH

指向函数的指针的声明可能看起来很愚蠢

char * ( *fp )( const char * ) = strinv;

要取消引用指针并调用指向的函数,您可以编写

( *fp )( s );

虽然写就够了

fp( s );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2013-01-25
    相关资源
    最近更新 更多