XOR C 中来自 argv 的两个字符串



想要XOR从argv获取的两个字符串。我检查了这个问题如何在 C 中 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] = '';
  printf("XOR: %sn",output);
  return 0;
}

当我使用 lldb 调试我的输出("(lldb) 打印输出")时,它是/a/x16/t/x13,但它不能由 printf() 打印。我知道它不再是字符串了。你能帮我如何让它能够被打印吗?终端中打印的文本为"XOR:"

代码中存在一些内存错误。也许以下方法会更好:

#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] = '';
  /* 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: %sn", output);
  return 0;
  }

printf而言,请记住 x ^ x = 0,并且 是 C 中的字符串终止符。

祝你好运。

最新更新