I created the four in a row game in c. Now I want to dynamically allocate the memory of the board. It is a two-dimensional array and I want it stored there for use. I declare it as a global double-pointer and declare it in my initialization method in the code below. I am new to c and I'm not entirely sure how to go about handling the segmentation fault(core dumped) error that I get.
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 50
//size of board
#define rows 6
#define column 7
//player's name
char player1[100];
char player2[100];
//pointer to keep track of playes turn
char *playersTurn;
//counter to keep track of where we are on each column
int a = rows - 1;
int b = rows - 1;
int c = rows - 1;
int d = rows - 1;
int e = rows - 1;
int f = rows - 1;
int g = rows - 1;
//array of the board
//int board[rows][column];
int **board;
//boardlaying array elements
void boardlayArray(){
printf("Two Dimensional array elements:\n");
for(int i=0; i<rows; i++) {
for(int j=0;j<column;j++) {
printf("%d ", board[i][j]);
if(j==6){
printf("\n");
}
}
}
}
//recostruct board to empty places
void teardown(){
/*Counter variables for the loop*/
int i, j;
for(int i=0; i<rows; i++) {
for(int j=0;j<column;j++) {
board[i][j]=0;
}
}
boardlayArray();
}
//checks if the four in a row are the same
int checkFour(int a, int b, int c, int d){
return a == b && b == c && c == d;
}
//check for the horizontal win
void checkHorizontal(int player){
for(int i=0; i < rows; i++){
for(int j=0; j < column - 3; j++){
if ((board[i][j] != 0) && (board[i][j+1] != 0) && (board[i][j+2]!= 0) && (board[i][j+3] != 0)){
if (checkFour(board[i][j],board[i][j+1],board[i][j+2],board[i][j+3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//check for vertical win
void checkVertical(int player){
for(int j=0; j < column; j++){
for(int i=rows - 1; i > rows - 3; i--){
if ((board[i][j] != 0) && (board[i-1][j] != 0) && (board[i-2][j]!= 0) && (board[i-3][j] != 0)){
if (checkFour(board[i][j],board[i-1][j],board[i-2][j],board[i-3][j]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//check for diagonal win
void checkDiagonal (int player){
// ascendingDiagonalCheck
for (int i=3; i<column; i++){
for (int j=0; j<rows-3; j++){
if ((board[i][j] != 0) && (board[i-1][j+1] != 0) && (board[i-2][j+2]!= 0) && (board[i-3][j+3] != 0)){
if (checkFour(board[i][j],board[i-1][j+1],board[i-2][j+2],board[i-3][j+3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
// descendingDiagonalCheck
for (int i=3; i<column; i++){
for (int j=3; j<rows; j++){
if ((board[i][j] != 0) && (board[i-1][j-1] != 0) && (board[i-2][j-2]!= 0) && (board[i-3][j-3] != 0)){
if (checkFour(board[i][j],board[i-1][j-1],board[i-2][j-2],board[i-3][j-3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//places the players puck into the correct place and gives it a corresponding value
//Also checks and correspondingly updtaes the turn to same player if row is full
int updateWorld(char w, int playerNumber){
switch(w)
{
case 'A':
if(a == -1){
printf("This row is full\n");
return 0;
}
board[a][0] = playerNumber;
a--;
break;
case 'B' :
if(b == -1){
printf("This row is full\n");
return 0;
}
board[b][1] = playerNumber;
b--;
break;
case 'C' :
if(c == -1){
printf("This row is full\n");
return 0;
}
board[c][2] = playerNumber;
c--;
break;
case 'D' :
if(d == -1){
printf("This row is full\n");
return 0;
}
board[d][3] = playerNumber;
d--;
break;
case 'E' :
if(e == -1){
printf("This row is full\n");
return 0;
}
board[e][4] = playerNumber;
e--;
break;
case 'F' :
if(a == -1){
printf("This row is full\n");
return 0;
}
board[f][5] = playerNumber;
f--;
break;
case 'G' :
if(g == -1){
printf("This row is full\n");
return 0;
}
board[g][6] = playerNumber;
g--;
break;
case ' ' : printf("Nothing was entered\n");
break;
case 'Q' : printf("%s has quit game\n", playersTurn);
teardown();
exit(0);
break;
default: printf("Enter a wrong option\n");
}
boardlayArray();
checkHorizontal(playerNumber);
checkVertical(playerNumber);
checkDiagonal(playerNumber);
return 1;
}
//get player's names and dynamicaaly allocate memory for board
void initialization(){
printf("Enter the name of player 1:\n");
fgets(player1,MAX, stdin);
printf("Enter the name of player 2:\n");
fgets(player2,MAX, stdin);
board = (int **)malloc(rows * sizeof(int *));
for (int i=0; i<rows; i++)
board[i] = (int *)malloc(column * sizeof(int));
}
//get where player wants to play
char acceptInput(){
printf("Enter where you want to put the disc A-G. Enter Q if you want to quit.\n");
char w;
scanf("%[^\n]",&w);
return w;
}
int main(){
initialization();
char w;
//runs for the size of the board
for(int i = 1; i <= (rows * column); i++){
w = acceptInput();
w = toupper(w);
if(i%2 == 0){
playersTurn = (char*) player2;
if(updateWorld(w,2) == 0){
playersTurn = (char*) player1;
printf("%s won the game",playersTurn);
exit(0);
}
}
else{
playersTurn = (char*) player1;
if(updateWorld(w,1) == 0){
playersTurn = (char*) player2;
printf("%s won the game",playersTurn);
exit(0);
}
}
while(getchar() != '\n');
}
return 0;
}
How About using the heap?? That's the goto of a programmer for dynamic memory allocation , here is a simple 2d array allocation code :
int main()
{
int r = 3, c = 4, i, j, count;
int *arr[r];
//allocating memory for an array
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
/*code to debug */
//free memory before allocating again
for(i=0; i<r; i++)
free(arr[i]);
//reallocating memory for an array
for(i=0; i<r+2; i++)
arr[i] = (int *)malloc(c * sizeof(int));
return 0;
/* code to work on reallocated array */
}
Related
I am trying to create a program to solve a wordsearch from a 2D array using only pointers. In my primary function for doing the actual search for the words I have a while loop that is supposed to keep going as long as i doesn't exceed the length of the word and as long as the letters from the word correspond to the letters on the grid. After finding the word it should make the letters on the grid lowercase and print out that it found the word. Here is my entire program right now.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void printPuzzle(char** arr, int n);
void searchPuzzle(char** arr, int n, char** list, int listSize);
void searchWord(int j, int k, int gridsize, char** arr, char** list, int listPos);
int main(int argc, char **argv) {
int bSize = 15;
if (argc != 2) {
fprintf(stderr, "Usage: %s <puzzle file name>\n", argv[0]);
return 2;
}
int i, j;
FILE *fptr;
char **block = (char**)malloc(bSize * sizeof(char*));
char **words = (char**)malloc(50 * sizeof(char*));
fptr = fopen(argv[1], "r");
if (fptr == NULL) {
printf("Cannot Open Puzzle File!\n");
return 0;
}
for(i=0; i<bSize; i++){
*(block+i) = (char*)malloc(bSize * sizeof(char));
fscanf(fptr, "%c %c %c %c %c %c %c %c %c %c %c %c %c %c %c\n", *(block+i), *(block+i)+1, *(block+i)+2, *(block+i)+3, *(block+i)+4, *(block+i)+5, *(block+i)+6, *(block+i)+7, *(block+i)+8, *(block+i)+9, *(block+i)+10, *(block+i)+11, *(block+i)+12, *(block+i)+13, *(block+i)+14 );
}
fclose(fptr);
fptr = fopen("states.txt", "r");
if (fptr == NULL) {
printf("Cannot Open Words File!\n");
return 0;
}
for(i=0; i<50; i++){
*(words+i) = (char*)malloc(20 * sizeof(char));
fgets(*(words+i), 20, fptr);
}
for(i=0; i<49; i++){
*(*(words+i) + strlen(*(words+i))-2) = '\0';
}
printf("Printing list of words:\n");
for(i=0; i<50; i++){
printf("%s\n", *(words + i));
}
printf("\n");
printf("Printing puzzle before search:\n");
printPuzzle(block, bSize);
printf("\n");
searchPuzzle(block, bSize, words, 50);
printf("\n");
printf("Printing puzzle after search:\n");
printPuzzle(block, bSize);
printf("\n");
return 0;
}
void printPuzzle(char** arr, int n){
for(int i = 0; i < n; i++){
printf("\n");
for(int j = 0; j < 15; j++){
printf("%c ", *(*(arr+i)+j));
}
}
}
void searchPuzzle(char** arr, int n, char** list, int listSize){
for(int i = 0; i < listSize; i++){
for(int j = 0; j < 15; j++){
for(int k = 0; k < 15; k++){
searchWord(j, k, 15, arr, list, i);
}
}
}
}
void searchWord(int j, int k, int gridsize, char** arr, char** list, int listPos){
int wordlength = strlen(*(list+listPos));
if(j+wordlength <= gridsize){ //Horizontal
int i = 0;
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+k) = tolower(*(*(arr+(j+i))+k));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++)
printf("%c", *(*(list+listPos)+i));
}
}
if(k+wordlength <= gridsize){ //Vertical
int i = 0;
while(i < wordlength && *(*(arr+j)+(k+i)) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+j)+(k+i)) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+k) = tolower(*(*(arr+(j+i))+k));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++){
printf("%c", *(*(list+listPos)+i));
}
}
}
if(j+wordlength <= gridsize && k+wordlength <= gridsize){ //Diagonal
int i = 0;
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+(j+i))+(k+i)) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+(k+i)) = tolower(*(*(arr+(j+i))+(k+i)));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++)
printf("%c", *(*(list+listPos)+i));
}
}
}
This is the part I believe there is a problem with.
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
If I print out the decimal value of i after this while loop it should at some point approach the length of one of the words as I know some words are horizontal, however every time it loops through and prints the value of i it never exceeds 1 which means the while loop never runs more than once which is impossible with the wordsearch files I am using to test this. What is causing this to happen? It is also 0 or 1 for every other direction when I try, the example above was just the while loop from the horizontal search.
There may also be a problem with the function searchPuzzle and the amount it loops through. However, I think that may be just my imagination.
Additional Info: The grid is 15x15 and there are 50 words in the list.
I think that you might need to declare Wordsearch again after the && -
while(i < wordlength && wordlength *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}
By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}
int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.
My program takes 3 lines of input. The first line being whether you want to sort it by odd or even, the second line being how large your array is and the third line being the integers in the array. It works until you use an array larger than 8. I believe it's to do with malloc but I've tried to debug this code for a couple of hours now and I can't fix this issue.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* sort;
int n;
int* ar;
int i;
int test()
{
int temp;
int j = 1;
//printf("%s", sort);
if (strcmp(sort, "odd") == 0) {
for (i = 0; i < n;) {
if (j != n) {
if (ar[i] % 2 != 0) {
if (ar[j] % 2 != 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
if (strcmp(sort, "even") == 0) {
for (i = 0; i < n; i++) {
if (j != n) {
if (ar[i] % 2 == 0) {
if (ar[j] % 2 == 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
}
void main()
{
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
//printf("%s", sort);
printf("Enter the elements of the array \n");
for (i = 0; i < n; i++) {
scanf("%d", &ar[i]);
}
test();
for (i = 0; i < n; i++) {
printf("%d ", ar[i]);
}
// return 0;
}
Code is typically executed in a linear fashion, but you don't seem to be doing that. You're allocating ar using n, but don't have a value for n yet until several lines later...
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
You're also not allocating the size of sort big enough to contain any string longer than 1 character.
I'm trying to figure out why I cannot delete elements from the dict array. Could somebody help me out? The function removeWord is working as it is supposed to when removing the last added word, but not when trying to remove some other word.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUMBER_OF_WORDS 11
int clear(){
while(getchar()^'\n');
return 0;
}
int numberOfWordsInDict(char **dict){
int i = 0;
int c1 = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] != 0){
c1++;
}
}
return c1;
}
void addWord(char **dict, char *word){
int c1 = numberOfWordsInDict(dict);
char *word1;
if (c1 >= 0 && c1 < 10){
word1 = (char*) malloc(sizeof(char)*(strlen(word)+1));
dict[c1] = word1;
strncpy(dict[c1], word, strlen(word));
dict[c1][strlen(word)] = '\0';
} else if (c1 >= 10){
printf("Dictionary is already full!\n");
}
}
void printDict(char **dict){
int i = 0;
int c1 = numberOfWordsInDict(dict);
printf("Dictionary:\n");
if (c1 == 0){
printf("The dictionary is empty.\n");
} else if (c1 > 0 && c1 <= 10){
while (dict[i] != NULL){
printf("- %s\n", dict[i]);
i++;
}
}
}
void removeWord(char **dict, char *word){
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
if (strncmp(dict[i], word, strlen(word)+1) == 0){
dict[i] = 0;// can only delete the last element of dict properly.
break;
}
}
}
int main(){
char *dict[MAX_NUMBER_OF_WORDS] = {};
char word[1024] = {};
char command;
while(1){
printf("Command (a/p/r/q): ");
while(scanf("%s", &command) == 1){
break;
}
;
clear();
if (command == 'a'){ // add word
scanf("%[^\n]s", &word);
clear();
addWord(dict, word);
} else if (command == 'p'){ // print dict
printDict(dict);
} else if (command == 'r'){ // remove word
printf("Remove a word: ");
scanf("%[^\n]s", &word);
clear();
removeWord(dict, word);
} else if (command == 'q'){ // quit
break;
}
}
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
free(dict[i]);
}
return 0;
}
example input:
a
dog
a
cat
a
apple
case 1:
r
apple
p
// output =
Dictionary:
- dog
- cat
a
uniform
p
// output =
Dictionary:
- dog
- cat
- uniform
// works fine
case 2
r
cat
p
// output =
Dictionary:
- dog
a
book
p
// output =
Dictionary:
- dog
// doesn't work as expected
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUMBER_OF_WORDS 11
int clear(){
while(getchar()^'\n');
return 0;
}
int numberOfWordsInDict(char **dict){
int c1 = 0;
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] != 0){
c1++;
}
}
return c1;
}
int vacancy(char **dict){
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] == 0){
return i;
}
}
return -1;
}
void addWord(char **dict, char *word){
int c1 = vacancy(dict);//It is not possible to use the registration number as an additional index.
if (-1 != c1){
dict[c1] = malloc(strlen(word)+1);
strcpy(dict[c1], word);
} else {
printf("Dictionary is already full!\n");
}
}
void printDict(char **dict){
int c1 = numberOfWordsInDict(dict);
printf("Dictionary:\n");
if (c1 == 0){
printf("The dictionary is empty.\n");
} else {
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if(dict[i])
printf("- %s\n", dict[i]);
}
}
}
void removeWord(char **dict, char *word){
for(int i = 0; i < MAX_NUMBER_OF_WORDS; i++){
if (strcmp(dict[i], word) == 0){
free(dict[i]);//need free
dict[i] = 0;// can only delete the last element of dict properly.
break;
}
}
}
int main(){
char *dict[MAX_NUMBER_OF_WORDS] = { NULL };
char word[1024] = { 0 };//forbids empty initializer braces
char command;
while(1){
printf("Command (a/p/r/q): ");
scanf("%c", &command);//%s buffer over run
clear();
if (command == 'a'){ // add word
scanf("%[^\n]", word);
clear();
addWord(dict, word);
} else if (command == 'p'){ // print dict
printDict(dict);
} else if (command == 'r'){ // remove word
printf("Remove a word: ");
scanf("%[^\n]", word);
clear();
removeWord(dict, word);
} else if (command == 'q'){ // quit
break;
}
}
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
free(dict[i]);
}
return 0;
}
Inside printDict() use
while (i<MAX_NUMBER_OF_WORDS){
if(dict[i] != 0)
printf("- %s\n", dict[i]);
i++;
}
instead of
while (dict[i] != NULL){
printf("- %s\n", dict[i]);
i++;
}
because even if you know if there are c1 number of words, you don't know their location as in where those c1 words are present.
Also change
while(scanf("%s", &command) == 1)
to
while(scanf("%c", &command) == 1)
since command is of char type.
I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}