c - What is with the null character in reverse string program? -
i had make simple program reverse string. got code own understanding google since couldn't work. runs fine , outputs should , understand of except reverse[j] = '\0'
statement. kept getting symbols in output when didn't state want know how works. can explain please?
#include<stdio.h> int main(void) { char original[20], reverse[20]; int length, i, j; printf("enter string:\n"); gets(original); length = strlen(original); (i = length - 1, j= 0; >= 0; i--, j++) reverse[j] = original[i]; reverse[j] = '\0'; //i don't know statement printf("the string reversed is:\n %s\n", reverse); return 0; }
if want character array contain string has have terminating zero.
for example function strlen
used in program counts characters in character array before terminating zero.
also function printf
used format specifier %s
outputs characters character array until terminating 0 encountered.
for example if have array this
char s[10] = "hello";
then call strlen( s )
returns 5 instead of 10. , call printf( "%s\n", s ); outputs 6 characters (including new line character).
consider demonstrative program
#include <stdio.h> int main(void) { char s[10] = "hello"; printf( "%d\n", printf( "%s\n", s ) ); return 0; }
its output is
hello 6
this initialization
char s[10] = "hello";
is equivalent to
char s[10] = { 'h', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0'};
if need reverse string stored in array obvious need reverse characters before first terminating zero. , if want copy string in reversed order character array need append destination array terminating zero.
this loop
for (i = length - 1, j= 0; >= 0; i--, j++) reverse[j] = original[i];
copies in reversed order characters except terminating 0 original character array starting last character before terminating 0 destination character array. need append destination character array terminating zero
reverse[j] = '\0';
Comments
Post a Comment