32
#include <stdio.h>

int main ()
{
    char *ptr = "stackoverflow"

}

Is there any way to find the length of stackoverflow pointed by ptr, as sizeof ptr always gives 4

Manu
  • 5,534
  • 6
  • 32
  • 42

11 Answers11

58

Use strlen to find the length of (number of characters in) a string

const char *ptr = "stackoverflow";
size_t length = strlen(ptr);

Another minor point, note that ptr is a string literal (a pointer to const memory which cannot be modified). Its better practice to declare it as const to show this.

Omer Dagan
  • 14,868
  • 16
  • 44
  • 60
simonc
  • 41,632
  • 12
  • 85
  • 103
  • 2
    +1 for two good practices, assigning string literals to `const char *` and use of `size_t` – effeffe Nov 25 '12 at 13:11
  • 2
    Indeed - just be careful that if the target is not a null terminated string, this will measure until it either randomly finds a null in memory, or triggers a memory protection fault in the course of that search. And of course (as others have pointed out) the returned value does not include the size of the terminating null. – Chris Stratton Mar 13 '15 at 12:29
  • size_t strLen = strlen(palavra); printf("Size of String >> %zu", strLen); For some reason mine shows lenght 0 – Raul Chiarella Nov 04 '22 at 06:40
29
  1. sizeof() returns the size required by the type. Since the type you pass to sizeof in this case is a pointer, it will return size of the pointer.

    If you need the size of the data pointed by a pointer you will have to remember it by storing it explicitly.

  2. sizeof() works at compile time. so, sizeof(ptr) will return 4 or 8 bytes typically. Instead use strlen.

Community
  • 1
  • 1
immayankmodi
  • 8,210
  • 9
  • 38
  • 55
7

The strlen() function provided by string.h gives you how many "real characters" the string pointed by the argument contains. However, this length does not include the terminating null character '\0'; you have to consider it if you need the length to allocate memory.

That 4 bytes is the size of a pointer to char on your platform.

kapil
  • 625
  • 12
  • 20
effeffe
  • 2,821
  • 3
  • 21
  • 44
7
#include<stdio.h>
main()
{
    int mystrlen(char *);
    char str[100];
    char *p;
    p=str;
    printf("Enter the string..?\n");
    scanf("%s",p);
    int x=mystrlen(p);
    printf("Length of string is=%d\n",x);


}
int mystrlen(char *p)
{
    int c=0;
    while(*p!='\0')
    {
        c++;
        *p++;
    }
    return(c);
}

simple code to understand

  • 1
    This if by far the best answer rather than just pointing out a built in method. – mLstudent33 Dec 19 '19 at 08:57
  • You can just use *p instead of *p!='\0' in while loop. – Jakob Apr 15 '20 at 01:43
  • I know this is an old answer, but what would happen if `p` pointed to a character and not a string literal? I tested this with the standard `strlen` function, and it seems to return nonsense. – steph Oct 30 '21 at 21:17
  • why use '*p++', p++ would do right ? since p is the pointer reference and *p is the first char pointed. *p++ still works but you are making a value reference that isn't used. – TheAnimatrix Oct 27 '22 at 08:48
1

You are looking for the strlen() function.

amit
  • 175,853
  • 27
  • 231
  • 333
1

You can try using:

char *ptr = "stackoverflow"
size_t len = strlen(ptr);
Blachshma
  • 17,097
  • 4
  • 58
  • 72
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

if ptr length is an argument of a function it's reasonable to use pointers as a strings. we can get string length by following code:

char *ptr = "stackoverflow";
length=strlen((const char *)ptr);

And for more explanation, if string is an input string by user with variable length, we can use following code:

unsigned char *ptr;
ptr=(unsigned char *)calloc(50, sizeof(unsigned char));
scanf("%s",ptr );
length=strlen((const char *)ptr);
Parham
  • 21
  • 2
  • 6
1

Purely using pointers you can use pointer arithmetic:

int strLen(char *s)
{
    int *p = s;
    while(*p !=’\0’)
    {
        p++;  /* increase the address until the end */
    }
    Return p – s; /* Subtract the two addresses, end - start */
}
Kevinj22
  • 966
  • 2
  • 7
  • 11
1

Even though this is a generic C question, it gets pretty high hits when looking this question up for C++. Not only was I in C/C++ territory, I also had to be mindful of Microsoft's Security Development Lifecycle (SDL) Banned Function Calls for a specific project which made strlen a no-go due to,

For critical applications, such as those accepting anonymous Internet connections, strlen must also be replaced...

Anyway, this answer is basically just a twist on the answers from the others but with approved Microsoft C++ alternative function calls and considerations for wide-character handling in respect to C99's updated limit of 65,535 bytes.

#include <iostream>
#include <Windows.h>
int wmain()
{
    //  1 byte per char, 65535 byte limit per C99 updated standard
    //  https://stackoverflow.com/a/5351964/3543437
    const size_t ASCII_ARRAY_SAFE_SIZE_LIMIT = 65535; 

    //  Theoretical UTF-8 upper byte limit of 6; can typically use 16383 for 4 bytes per char instead:
    //  https://stijndewitt.com/2014/08/09/max-bytes-in-a-utf-8-char/
    const size_t UNICODE_ARRAY_SAFE_SIZE_LIMIT = 10922;

    char ascii_array[] = "ACSCII stuff like ABCD1234.";
    wchar_t unicode_array[] = L"Unicode stuff like → ∞ ∑ Σὲ γνωρίζω τὴν ደሀ ᚦᚫᛏ.";

    char * ascii_array_ptr = &ascii_array[0];
    wchar_t * unicode_array_ptr = &unicode_array[0];

    std::cout << "The string length of the char array is: " << strnlen_s(ascii_array_ptr, ASCII_ARRAY_SAFE_SIZE_LIMIT) << std::endl;
    std::wcout << L"The string length of the wchar_t array is: " << wcsnlen_s(unicode_array_ptr, UNICODE_ARRAY_SAFE_SIZE_LIMIT) << std::endl;

    return 0;
}

Output:

The string length of the char array is: 27
The string length of the wchar_t array is: 47
kayleeFrye_onDeck
  • 6,648
  • 5
  • 69
  • 80
0

strlen() gives you the exact length of the string [excluding '\0']

sizeof() gives you the size of the data type used.

// stackoverflow = 13 Characters
const char* ptr = "stackoverflow";

strlen(ptr);             // 13 bytes - exact size (NOT includes '\0')
sizeof(ptr);             // 4  bytes - Size of integer pointer used by the platform
sizeof(*ptr);            // 1  byte  - Size of char data type

strlen("stackoverflow"); // 13 bytes - exact size
sizeof("stackoverflow"); // 14 bytes - includes '\0'
SridharKritha
  • 8,481
  • 2
  • 52
  • 43
0
#include<stdio.h>

int main() {
char *pt = "String of pointer";
int i = 0;
while (*pt != '\0') {
    i++;
    pt++;
}
printf("Length of String : %d", i);
return 0;
}

We can also use strlen() function or sizeof() operator which is builtin in C. We can also take help of pointer arithmetic as above example.

Amrit Raj
  • 39
  • 3
  • In this case, `sizeof()` will evaluate to the size of a pointer, not the length of the string. Did you read the other answers before posting a redundant and inaccurate one? – chqrlie Sep 28 '22 at 12:27