When I am trying to do a bitwise XOR of two strings, I get x��K or similar output. The code I am using:
char test[] = "teststring";
char test2[] = "testtwostring";
char *bytearray = NULL;
bytearray = malloc(sizeof(char) * (strlen(test2)+1));
for(int j=0; (j< strlen(test) && j< strlen(test2)); j++){
bytearray[j] += test[j] ^ test2[j];
}
printf(bytearray)
Should it not save the XOR result of both string, in each of the bytearray elements, and then print out a new result string? Is there something I am missing?
You haven't initialized
bytearray, so it contains whatever garbage happened to be in that section of memory when it was allocated. You want to do:after you allocate the array with
malloc(). As @John Bollinger noted, you can combine themallocandmemsetby callingcalloc:As another alternative, you could just assign instead of adding:
instead of:
Also, you shouldn't call
strlenrepeatedly, since the value will never change. You should just call it once each fortestandtest2, store those values in variables, and use the variables. Right nowstrlenis getting unnecessarily called twice each time yourforloop iterates.