简体   繁体   English

如何在 function 中获取字符串长度

[英]How to get string length in function

How can I get the length of the buffer in the function using pointers?如何使用指针获取 function 中缓冲区的长度?

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

void fun(char *(buffer))
{
    printf(strlen(buffer));
}

int main()
{
    char buffer[] = "Hello";
    fun(&buffer);

    return 0;
}

You need to include the header您需要包括 header

#include <string.h>

then in the function to write然后在function中写

void fun(char *buffer)
{
    printf( "%zu\n", strlen( buffer ) );
}

or或者

void fun(char *buffer)
{
    size_t n = strlen( buffer );
    printf( "%zu\n", n );
}

and at last to call the function like最后像这样调用 function

fun( buffer );

If you need to get the length of the passed string within the function yourself without using the standard string function strlen then the function can look like如果您需要在不使用标准字符串 function strlen的情况下自己获取 function 中传递的字符串的长度,那么 function 可以看起来像

void fun(char *buffer)
{
    const char *p = buffer;

    while ( *p ) ++p;
    size_t n = p - buffer;

    printf( "%zu\n", n );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM