从C中的argv中取出两个字符串

时间:2017-10-27 19:31:15

标签: c string xor argv

想要从argv中取出两个字符串。 我查看了这个问题How to xor two string in C?,但它无法为我解决。

#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;
}

当我使用 lldb 调试输出(“( lldb )打印输出”)时,它是 / a / x16 / t / x13 但是printf()无法打印。我知道它不再是一个字符串了。你能帮我解决一下如何使它成为printf:ed。 终端中打印的文本是“XOR:”

1 个答案:

答案 0 :(得分: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中的字符串终止符。

祝你好运。