Home > OS >  C String with size
C String with size

Time:12-16

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);

CodePudding user response:

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.

  • Related