Well, here are my solutions. If anyone happens to read this, I'd appreciate any comments on the correctness/incorrectness of my code.
Using only pointers: declare an array of signed integers and assing it a size of 50 integers.
(I'm not sure if I fully understood this exercise, but here's what I got anyway:)
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* example = (int*) malloc(50*sizeof(int));
free(example);
return 0;
}
[/spoiler]
Same as the last exercise but also assign positions 5, 6, and 8, and then print them.
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* example = (int*) malloc(50*sizeof(int));
*(example + 5) = 10;
*(example + 6) = 12;
*(example + 8) = 20;
printf("%d, %d, %d", example[5], example[6], example[8]);
free(example);
return 0;
}
[/spoiler]
Using only pointers: given a random string, print from the 5th character onwards.
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* random = "this is a random string";
char* print = random + 4;
printf("%s", print);
return 0;
}
[/spoiler]
Given 2 strings of length 5, encrypt the first one using the second one using an XOR operation.
[spoiler]
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* string0 = "abcde";
char* string1 = "qwert";
char* encrypted = malloc(6);
memset(encrypted, 0, 6);
*encrypted = *string0 ^ *string1;
*(encrypted+1) = *(string0+1) ^ *(string1+1);
*(encrypted+2) = *(string0+2) ^ *(string1+2);
*(encrypted+3) = *(string0+3) ^ *(string1+3);
*(encrypted+4) = *(string0+4) ^ *(string1+4);
printf("%s\n", encrypted);
free(encrypted);
return 0;
}
[/spoiler]
This one doesn't quite work as I think it is supposed to. However, I think it does sort of work. The integer value of each character is XORed with the integer value of the corresponding character in the second string. As it happens, the results are not valid characters when printed as characters. But XORing them again with the same characters from the second string does return the original string. e.g.
[spoiler]
Code: Select all
char* dec = malloc(6);
*dec = *encrypted ^ *string1;
*(dec+1) = *(encrypted+1) ^ *(string1+1);
*(dec+2) = *(encrypted+2) ^ *(string1+2);
*(dec+3) = *(encrypted+3) ^ *(string1+3);
*(dec+4) = *(encrypted+4) ^ *(string1+4);
printf("%s", dec);
free(dec);
[/spoiler]
I think maybe I didn't fully understand this exercise. I'm guessing I was not meant to XOR each character with the corresponding character from the second string. However, I am not altogether sure what I
was meant to do. Guess I'll have a look at other people's solutions.
EDIT: Looking at other solutions, and the comments made on them, I think these are correct. I fixed my last solution because before I cast each char as an int before XORing them, but m0skit0 pointed out earlier in the thread that that is unnecessary and wastes memory. Still, any more comments on my code are welcome.