Is it possible to create string variables using pointers? So that I don’t have to pass its size everytime, like char x[4] = “aaa”?
How can I get the size of such string?
And can I initialize an empty string with a pointer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Remember that strings in C are ended by the null terminator character, written as
\0. If you have a well-formed string stored in your pointer variable, you can therefore determine the length by searching for this character:If your variables are uninitialized or otherwise not well-formed (e.g., by being
NULL) you obviously cannot take this approach; however, most functions are generally written under the assumption that the strings are well-formed, because this leads to faster code.If you wish to initialize a pointer, you have three options:
NULL, a valid address (e.g.,char *x = &someCharVar), or a string constant (e.g.,char *x = "hello"). Note that if you use a string constant, it is illegal for you to write into that pointer unless you re-assign to it with the address of a non-constant string.Note that
sizeof(char)is unnecessary here, since acharis always defined to be exactly 1 byte. However, it’s a good habit to get into for when you’re using other data types, and it helps make your code self-documenting by making your intentions very clear.