2017-10-27 59 views
0

argvからフェッチされた2つの文字列をXORしたい。 この質問はHow to xor two string in C?でしたが、解決できませんでした。私はそれが/A/X16/T/X13である私の出力( "(lldb)印刷出力")をデバッグするlldbを使用しますが、それはprintf関数で印刷することができないC言語のargvからXOR 2文字列

#include <stdio.h> 
#include <string.h> 

int main(int argc, char const *argv[]) { 
    char output[]=""; 

    int i; 
    for (i=0; i<strlen(argv[1]); i++){ 
     char temp = argv[1][i]^argv[2][i]; 
     output[i]= temp; 

    } 
    output[i] = '\0'; 
    printf("XOR: %s\n",output); 
    return 0; 
} 

() 。私はそれがもう文字列ではないことを知っています。印刷する方法を教えてください。 端末に表示されるテキストは「XOR」です

+0

これを参照してください。https://stackoverflow.com/questions/39262323/print-a-string-variable-with-its-special-characters –

+0

ここで、「出力」にスペースを割り当てましたか?あなたは現在の出力が何であるかを提示しましたが、期待される出力は何か言及できますか? [MCVE]の作成方法をご覧ください。 –

+3

あなたの 'output'は十分大きな配列のために割り当てられる必要があります。 – chrisaycock

答えて

1

コードにはいくつかのメモリ不具合があります。おそらく、以下のより良い仕事になります。

#include <stdio.h> 
#include <string.h> 

#define min(i, j) ((i) < (j) ? (i) : (j)) 

int main(int argc, char const *argv[]) 
    { 
    char *output; 
    int i; 

    /* Allocate a buffer large enough to hold the smallest of the two strings 
    * passed in, plus one byte for the trailing NUL required at the end of 
    * all strings. 
    */ 

    output = malloc(min(strlen(argv[1]), strlen(argv[2])) + 1); 

    /* Iterate through the strings, XORing bytes from each string together 
    * until the smallest string has been consumed. We can't go beyond the 
    * length of the smallest string without potentially causing a memory 
    * access error. 
    */ 

    for(i = 0; i < min(strlen(argv[1]), strlen(argv[2])) ; i++) 
     output[i] = argv[1][i]^argv[2][i]; 

    /* Add a NUL character on the end of the generated string. This could 
    * equally well be written as 
    * 
    * output[min(strlen(argv[1]), strlen(argv[2]))] = 0; 
    * 
    * to demonstrate the intent of the code. 
    */ 

    output[i] = '\0'; 

    /* Print the XORed string. Note that if characters in argv[1] 
    * and argv[2] with matching indexes are the same the resultant byte 
    * in the XORed result will be zero, which will terminate the string. 
    */ 

    printf("XOR: %s\n", output); 

    return 0; 
    } 

限りprintfが行くように、x^x = 0ということと\0はC.

運のベスト

で文字列の終端であることに留意してください。

+0

私が見た最悪の機能の1つです。なぜ:https://godbolt.org/g/mcH8SU –

+0

あなたはPeterのリンクが何を示しているのですか? – EsmaeelE

関連する問題