Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the size of a string pointed by a pointer

Tags:

c

#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

like image 402
Manu Avatar asked Nov 25 '12 12:11

Manu


People also ask

How do you find the length of a string with a pointer?

The strlen() Function The strlen() accepts an argument of type pointer to char or (char*) , so you can either pass a string literal or an array of characters. It returns the number of characters in the string excluding the null character '\0' .

How do I find the length of a char in a string?

first, the char variable is defined in charType and the char array in arr. Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.

What is the size of for pointer?

It depends upon different issues like Operating system, CPU architecture etc. Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes.


1 Answers

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.

like image 88
simonc Avatar answered Sep 21 '22 03:09

simonc