1
votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *text1 = "Text von links nach rechts!";
    char text2[50] ;
    printf("ursprunglicher text ist : \n");
    printf(("%s\n\n",text1));
    int i = 0 ;
    
    
    while(*(text1+i) != '\0')
    {
        i++;
    }
    
    int j = 0;
    while(i >= 0)
    {
        text2[j] = text1[i];
        //printf("%c",*(text2+j));
        i--;
        j++;
    }
    *(text2 + strlen(text1)+1) = '\0';
    
    printf("%s",text2);
    return 0 ;
}

My printf statement prints nothing , I tried to print character by character in the while loop to check whether it's correct or not and it worked but didn't work while printing . The program normally swaps the text1 and copy it on the text2 .

1
text2[j] = text1[i]; Think hard about what is at text1[i] on the very first iteration of the second while-loop. Hint: Think about what broke you out of your prior loop. And fyi, *(text1+i) is synonymous with text1[i], so unless you're getting bonus points for writing obfuscated code, shoot for clarity. Cryptic != better.WhozCraig

1 Answers

2
votes

When the first loop ends, text1[i] is the null terminator byte. So you copy this null byte to the first element of text2, therefore text2 is viewed as an empty string.

You should subtract 1 from i before the copying loop.

     while(*(text1+i) != '\0')
     {
         i++;
     }
     i--;

The first loop and this subtraction can be replaced with:

    i = strlen(text1) - 1;