Last active
June 9, 2019 02:45
-
-
Save nacersalaheddine/00a125051da10187cb358ad919a33aa6 to your computer and use it in GitHub Desktop.
Calculate the length of a string in C lang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
/* | |
Author:nacer salah eddine. | |
Description:Calculate the length of a string in C lang. | |
Compile: | |
gcc strlen.c -std=c99 -Wall -o strlength | |
*/ | |
size_t size_of_string(const char* str){ | |
/* | |
Put the @(address) of pointer str into the pointer p | |
Example: | |
str has,str:0040803c | |
assign can be done in 2 ways | |
1- | |
register const char *p = str; | |
2- | |
register const char *p; | |
p = str; | |
p has,str:0040803c | |
*/ | |
register const char *p = str; | |
/* | |
loop until u reach the end of the string ('\0') | |
increase the value of pointer p during that. | |
finally return the difference between p and str | |
Example: | |
str at first has,str:0040803c | |
p at end has, p:0040804b | |
p - str ==(equals) F (in hex) | |
F == 15 (DECIMAL) | |
Note:To print the value of any pointer here use | |
printf("%p \n",p); | |
*/ | |
while(*p){ | |
p++; | |
} | |
return (p-str); | |
} | |
int main(){ | |
const char *string = "hello bad world\0"; | |
int str_size = size_of_string(string); | |
printf("%d\n",str_size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment