I am trying to swap two pointers in the same array 52 times using a function within a for-loop. I am getting a segmentation fault and i'm not sure where the issue is.
Here's my code:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "shuffle.h"
extern void shuffle(int** tempPtr1 , int** tempPtr2);
extern void deal(int numPlayers, int numHands, int** tempPtr2);
int main(void) {
int numPlayers;
int numHands;
int randomNum;
printf("Enter number of players: ");
scanf("%d", &numPlayers);
printf("Enter number of hands per player: ");
scanf("%d", &numHands);
int card[52] = {0};
char faces[] = {'A', '2', '3', '4', '5', '6', '7', '8', '9','X', 'J', 'Q', 'K'};
char suit[] = {'S', 'D', 'H', 'C'};
srand((unsigned)time(NULL));
for(int i = 0; i < 52; i++) {
card[i] = suit[i/13];
card[i] = card[i] << CHAR_BIT;
card[i] = card[i] | faces[i%13];
}
int *firstIndxPtr;
firstIndxPtr = &card[0];
int *randIndxPtr1;
for(int i = 0; i<52;i++){
randomNum = rand() % 52 + 1;
randIndxPtr1 = &card[randomNum];
shuffle(&firstIndxPtr, &randIndxPtr1);
}
deal(numPlayers, numHands, &firstIndxPtr);
}
and then my function shuffle:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int** tempPtr1 , int** tempPtr2);
void shuffle(int** tempPtr1 , int** tempPtr2)
{
int* tempPtr = *tempPtr2;
*tempPtr2 = *tempPtr1;
*tempPtr1 = tempPtr;
}
the function should swap the pointer address of the 0 index in the card array with the pointer address of a random index in the card array. This would then be done 52 times in the for loop, creating a fully shuffled array. Instead I get a segmentation fault.