0

How can I get the length of the buffer in the function using pointers?

#include <stdio.h> #include <stdlib.h> void fun(char *(buffer)) { printf(strlen(buffer)); } int main() { char buffer[] = "Hello"; fun(&buffer); return 0; } 
3
  • 1
    And what is the problem? Commented Sep 13, 2022 at 14:23
  • 1
    The string buffer is already a pointer, so & is not necessary in this example. Commented Sep 13, 2022 at 14:32
  • 2
    Save time. Enable all warnings to see trouble with printf(strlen(buffer));. Commented Sep 13, 2022 at 14:37

1 Answer 1

2

You need to include the header

#include <string.h> 

then in the function to write

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

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

void fun(char *buffer) { const char *p = buffer; while ( *p ) ++p; size_t n = p - buffer; printf( "%zu\n", n ); } 
Sign up to request clarification or add additional context in comments.

Comments