Home > Mobile >  Trying to output the length of a string using strlen() through a pointer
Trying to output the length of a string using strlen() through a pointer

Time:11-02

I am trying to output the length of a string using strlen(). But I want to do it through a pointer.

Here's what I tried: `

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

int main()
{
    char a[]="wel";
    int *p;
    p=&a;
    printf("%d\n",strlen(*p));
}

The image shows the error I am getting while compiling:enter image description here

Then made this change in the code declaration of *p to *p[]:

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

int main()
{
    char a[]="wel";
    int *p[];
    p=&a;
    printf("%d\n",strlen(*p));
}

But then I am getting an error "storage size of 'p' isn't known." What am I still missing?

CodePudding user response:

Except in a couple of limited circumstances (noteably sizeof), an array degrades into a pointer to its first element when used. So this is what you need:

char *p = a;   // Same as `p = &(a[0])`
printf( "%zu\n", strlen( p ) );

Note that strlen returns a size_t, and %zu is the correct format specifier for that.

CodePudding user response:

The declaration of the array a initialized with a string literal

char a[]="wel";

is equivalent to

char a[4]="wel";

So the expression &a has the type char ( * )[4] but the pointer p has the type int *

int *p;

and there is no implicit conversion between the pointer types.

And again the function strlen expects a pointer of the type char * but you are passing an expression of the type int

printf("%d\n",strlen(*p));

Also the return type of the function strlen is size_t. So at least you have to use the conversion specifier zu instead of d in the call of printf.

It seems what you mean is the following

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

int main()
{
    char a[]="wel";
    char *p;
    p = a;

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

In this assignment statement

p = a;

the array a used in the right hand side expression is implicitly converted to pointer to its first element of the type char *.

As for the second program then you declared an array of pointers without specifying the number of elements

int *p[];

Such a declaration is invalid.

And moreover arrays do not have the assignment operator that you are trying to use

p=&a;

So the second program in whole does not make sense.

CodePudding user response:

p is not a string, it is the pointer to type int. Why just not use

printf("%d\n",strlen(a));

Then use

char a[4]="wel";
  • Related