Feb 17, 2022 11:26 PM
(This post was last modified: Feb 17, 2022 11:34 PM by EmacsSucksButILikeIt.)
Fun C Challenge(Pointers, Random Integers, Arrays)..
Here's a fun and standard C problem. Can you shuffle an array of integers via an array of int pointers?
I.E.
Say you have an array of integers:
and an array of int pointers:
Now can you use the addresses of the elements in arr to populate arr_ptrs such that each address in arr is present in arr_ptrs only once and is shuffled.
Here's something to get you started:
Here is some examples of what the output of printing arr_ptrs would look like.
Notice that each number from arr is represented and the output is shuffled.
Here's a fun and standard C problem. Can you shuffle an array of integers via an array of int pointers?
I.E.
Say you have an array of integers:
Code
#define ARR_SIZE 10
int arr[ARR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};and an array of int pointers:
Code
#define ARR_SIZE 10
int *arr_ptrs[ARR_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};Now can you use the addresses of the elements in arr to populate arr_ptrs such that each address in arr is present in arr_ptrs only once and is shuffled.
Here's something to get you started:
Code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARR_SIZE 10
void shuffle(int arr[], int *arr_ptr[], size_t size) {
//Do your C magic here
}
int main(int argc, char **argv) {
size_t i = 0;
int arr[ARR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *arr_ptrs[ARR_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
shuffle(arr, arr_ptrs, ARR_SIZE);
for (; i < ARR_SIZE; i++) {
arr_ptrs[i] ?
fprintf(stdout, "(%ld): %d\n", i, *arr_ptrs[i]) :
fprintf(stdout, "(%ld): NULL value\n", i);
}
return 0;
}Here is some examples of what the output of printing arr_ptrs would look like.
Code
(0): 8
(1): 7
(2): 2
(3): 3
(4): 10
(5): 1
(6): 9
(7): 4
(8): 5
(9): 6Code
(0): 1
(1): 3
(2): 8
(3): 7
(4): 4
(5): 10
(6): 2
(7): 6
(8): 5
(9): 9Notice that each number from arr is represented and the output is shuffled.

