I need to define the characters in an array and print the string…But it always prints as string7 (in this case, test7)…What am I doing wrong here?
#include <stdio.h>
int main() {
char a[]={'t','e','s','t'};
printf("%s\n",a);
return 0;
}
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.
Because you did not
\0terminate your array, so what you get is Undefined behavior.The
printftries to print the string till it encounters a\0and in your case the string was never\0terminated so it prints randomly till it encounters a\0.Note that reading beyond the bounds of allocated memory is Undefined behavior so technically this is a UB.
You need:
or