i'm attempting a question which asks me to create a function called randSwap, that takes in 2 arrays of void pointers, and with a 50% chance, it will swap 2 values of the same index between the 2 arrays. Below is my code, but whenever i go to compile, it gives me several errors discussing:
warning: initialization makes pointer from integer without a cast.
void *array1[4] = {3,4,2,5};
and several others relating to array1 and 2.
When i run the program, the values of array1 becomes corrupted producing a large single integer, and array 2 prints its original values both times.
I am very unfamiliar with using void types, as I think this is where the problem lies.
#include <stdio.h>
int randSwap(void *array1[], void *array2[], int length)
{
static int numofswaps = 0;
int value;
int toswap;
void *temp;
value = rand() % 2;
if(value == 2)
{
toswap = rand() % length;
temp = array1[toswap];
array1[toswap] = array2[toswap];
array2[toswap] = temp;
numofswaps++;
}
return numofswaps;
}
int main(void)
{
int i;
void *array1[4] = {3,4,2,5};
void *array2[4] = {6,3,7,4};
int length = 4;
int numofswaps;
srand(time(NULL));
printf("Array1\n");
for(i=0; i<length; i++);
{
printf("%d\t", (int*)array1[i]);
}
printf("\nArray2\n");
for(i=0; i<length; i++)
{
printf("%d\t", (int*)array2[i]);
}
numofswaps = randSwap(array1, array2, length);
numofswaps = randSwap(array1, array2, length);
printf("\nArray1\n");
for(i=0; i<length; i++);
{
printf("%d\t", (int*)array1[i]);
}
printf("\nArray2\n");
for(i=0; i<length; i++)
{
printf("%d\t", (int*)array2[i]);
}
printf("\n");
return 0;
}
Aucun commentaire:
Enregistrer un commentaire