2017-10-27 38 views
0

argv에서 가져온 두 개의 문자열을 XOR로 보내고 싶습니다. 이 질문을 How to xor two string in C?으로 확인했지만 해결할 수 없었습니다. 나는 그것이 /A/16 배속/t/X13 내 출력 ("(lldb) 인쇄 출력")를 디버깅하는 lldb를 사용하지만이 printf와 인쇄 할 수 없습니다C에서 argv의 XOR 두 문자열

#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

여기서'output'을위한 공간을 할당 했습니까? 현재 출력물이 무엇인지 알려 주었지만 예상되는 출력물을 언급 할 수 있습니까? [MCVE]를 만드는 방법을 참조하십시오. –

+3

'출력'은 충분히 큰 배열에 할당해야합니다. – 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

내가 본 최악의 기능 중 하나입니다. 이유 : https://godbolt.org/g/mcH8SU –

+0

피터 링크에서 무엇을 보여줄지 알고 계십니까? – EsmaeelE