gpt4 book ai didi

c - 在 C 中对 argv 中的两个字符串进行异或

转载 作者:行者123 更新时间:2023-11-30 14:53:52 25 4
gpt4 key购买 nike

想要对从 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:”

最佳答案

您的代码中存在一些内存错误。也许以下内容会更好:

#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 中的字符串终止符。

祝你好运。

关于c - 在 C 中对 argv 中的两个字符串进行异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46982214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com