I want to copy the string “Best School” into a new space in memory, which of these statements can I use to reserve enough space for it
A. malloc(sizeof(“Best School”))
B. malloc(strlen(“Best School”))
C. malloc(11)
D. malloc(12)
E. malloc(sizeof(“Best School”) + 1)
F. malloc(strlen(“Best School”) + 1)
I am still very new to C programming language so I really am not too sure of which works well. But I will love for someone to show me which ones can be used and why they should be used.
Thank you.
>Solution :
Literal strings in C are really arrays, including the null-terminator.
When you use sizeof on a literal string, you get the size of the array, which of course includes the null-terminator inside the array.
So one correct way for a literal string would be sizeof("Best School") (or sizeof "Best School").
You can also use strlen. If you don’t have a string literal but another array or a pointer to the first character of the string, then you must use strlen. But now you have to remember that strlen returns the length of the string without the null-terminator. So you need to add one for that.
So another correct way would then be strlen("Best School") + 1.
Using magic numbers is almost never correct.