post the relevant code
post the relevant code
Output:Code:#include <stdio.h> #include <string.h> int main(){ char string[]="hello world"; char string2[100]; int i; for(i=0;i<=strlen(string);i++){ printf("strlen(string)-i= %d-%d = %d\n",strlen(string),i,strlen(string)-i); string2[i]=string[strlen(string)-i]; } printf("string=%s\n",string); printf("rstring=%s\n\n",string2); return 0; }
strlen(string)-i= 14-0 = 14
strlen(string)-i= 14-1 = 13
strlen(string)-i= 14-2 = 12
strlen(string)-i= 14-3 = 11
strlen(string)-i= 14-4 = 10
strlen(string)-i= 14-5 = 9
strlen(string)-i= 14-6 = 8
strlen(string)-i= 14-7 = 7
strlen(string)-i= 14-8 = 6
strlen(string)-i= 14-9 = 5
strlen(string)-i= 14-10 = 4
strlen(string)-i= 14-11 = 3
strlen(string)-i= 14-12 = 2
strlen(string)-i= 14-13 = 1
strlen(string)-i= 14-14 = 0
string=I am a string!
rstring=
Last edited by bertazoid; 02-08-2009 at 04:46 PM.
I think I got it. It's because it's putting the null termintor of string as the first element of string2.
that's exactly it
I changed the for loop to start at i=0, so it would exclude the null character at the end of the string, but my program still gives the same output - rstring is blank.
try this (starting a line 12):
rstring=dlrow ollehCode:if (i>0) string2[i-1]=string[strlen(string)-i]; } string2[i]='\0';
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
Thanks it worked, except instead of using the if statement, I just started the loop at i=1.
IMO you are getting confused between the length of string[] and the char stored at a particular index of the array string[].
So setting i=1 is the way to go.Code:string="I am a string!"; strlen(string)-i=14-0=14; /* i = 0 */ strlen(string)-i=14-1=13; /* i = 1 */ string[14] = NULL; /* char at index 14 is NULL */ string[13] = '!'; /* char at index 13 is '!' */