Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C String with size

I have this code in C. The function needs to know the length of the string. Is there no way for me to pass just the string and then, inside the function, get the size?

char text2[] = "Hello!!";
write_coord_screen(2, 2, text2, sizeof(text2), FB_BLACK, FB_WHITE);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Take a look at strlen. Notice however, that strlen is a O(n) operation, so if you know the length of the string (as you do in the above example) it may be preferable to pass that directly instead of computing it.

Also, in the above example, sizeof(text2) will be 8, but the length of the string is 7. sizeof will take into consideration the nul terminator, but usually when we talk about the length of a string we talk about the number of characters it has.

On top of this, sizeof only works in your case because char text2[] declares a character array. If instead you’d have written const char *text2 = "Hello!!" you’d be forced to use strlen.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading