Assistance needed with pointers and arrays - c

Ok, so I am writing a program that reads input from a file and puts them into arrays. I am trying to use pointers with arrays so I can point to a certain spot in an array and add a user defined float to the float that already exists.
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int menu1();
int main()
{
FILE * ifp = fopen("input2.txt","r"); //Open the input file
int cars = 5, i , j, k; // Initialized cars and counters i, j, and k
char *VIEW="VIEW", *BID="BID", *CLOSE="CLOSE", choice1[20]; //Initialize character arrays
float START_BID[5]={0.00}, MIN_BID[5]={0.00}, CUR_BID[5]={0.00}, USR_BID[5]=0.00};
int compareLimit = 100, selection=0;
//Scan the file and appropriate the numbers into their respective arrays
for (i = 0; i < cars; i++)
{
fscanf(ifp, "%f %f", &START_BID[i],&MIN_BID[i]);
}
printf("Welcome to the Silent Auction\n\n");
menu1(); //Display the menu
scanf("%s", &choice1); //
int result = strncmp(choice1, VIEW, compareLimit); //Compare two strings
if(result == 0)
{
selection = selection + 1;
}
int result2 = strncmp(choice1, BID, compareLimit); //Compare two strings
if(result2 == 0)
{
selection = selection + 2;
}
int result3 = strncmp(choice1, CLOSE, compareLimit); //Compare two strings
if(result3 == 0)
{
selection = selection + 3;
}
while (selection < 3)
{
if (selection == 1)
{
printf("Number\tCurrent Bid\tMinimum Increase\n");
printf("1\t$%.2f\t\t$%.2f\n",CUR_BID[0], MIN_BID[0]);
printf("2\t$%.2f\t\t$%.2f\n",CUR_BID[1], MIN_BID[1]);
printf("3\t$%.2f\t\t$%.2f\n",CUR_BID[2], MIN_BID[2]);
printf("4\t$%.2f\t\t$%.2f\n",CUR_BID[3], MIN_BID[3]);
printf("5\t$%.2f\t\t$%.2f\n",CUR_BID[4], MIN_BID[4]);
menu1();
scanf("%s", &choice1);
}
else if (selection == 2)
{
int k;
float usr_bid;
printf("Which auction would you like to bid on? (1-5)\n");
scanf("%d", k);
if (CUR_BID[k - 1] = 0.00)
MIN_BID[k - 1] = START_BID[k - 1];
else
MIN_BID[k - 1] = CUR_BID[k - 1] + MIN_BID[k - 1];
printf("The minimum bid is %.2f\n", MIN_BID[k - 1]);
printf("How much would you like to bid?\n");
scanf("%f", usr_bid);
if (usr_bid < MIN_BID[k-1])
printf("Sorry, that bid is not high enough.\n");
else
CUR_BID[k - 1] = usr_bid + CUR_BID[k - 1];
menu1();
scanf("%s", &choice1);
}
else
{
int i;
int auction = 1;
for (i=0; i < cars; i++)
{
for (auction = 1; auction < cars; auction++)
{
while (CUR_BID[i]!= 0.00)
printf("Auction %d sold for $%.2f", auction, CUR_BID);
}
}
}
}
fclose(ifp);
return 0;
}
int menu1()
{
printf("Please make a selection (In all caps):\n");
printf("\tView Auctions [VIEW]\n");
printf("\tBid on an Auction [BID]\n");
printf("\tClose Auctions [CLOSE]\n");
}
My program works up to the while loop where else if (selection == 2) is. It asks me which
auction I want. And when I give it a number, it just freezes, crashes, and doesn't give me any errors other than Process terminated with status -1073741510.
Any ideas?

The pointers you pass to scanf() are incorrect.
Change:
scanf("%d", k);
to
scanf("%d", &k);
and change:
scanf("%s", &choice1); //
to
scanf("%s", choice1); //
in two places.

Related

How to Fix the Logic Errors in My "Guess the Movie" Game as a C Program

I have written a Guess the Movie game in the C programming language. My logic seems to be correct but whenever I run the program, it doesn't work as expected.
Here is my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ran = 1;
int l, j = 0, i = 0, total = 0, d = 0;
char b;
char a[20];
char s[1000];
int z;
FILE *my;
printf("Enter your name:\n ");
scanf("%s", s);
ran = rand() % 6;
if (ran == 1)
{
my = fopen("my1.txt", "r");
}
else if (ran == 2)
{
my = fopen("my.txt", "r");
}
else if (ran == 3)
{
my = fopen("my2.txt", "r");
}
else if (ran == 4)
{
my = fopen("my3.txt", "r");
}
else if (ran == 5)
{
my = fopen("my4.txt", "r");
}
for (d = 0; d < 20; d++)
fscanf(my, "%c", &a[d]);
fclose(my);
printf("GUESS THE MOVIE GAME\n");
for (j = 0; j < 7; j++)
{
if (a[j] == 'm')
{
printf("M ");
}
else
{
printf("_ ");
}
}
printf("\n");
printf("Let's begin the game\n");
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
printf("enter character number %d\n",i+1);
scanf("%c", &b);
if (b == a[i])
{
printf("its a right guess\n");
total = total + 4;
i++;
}
else if (b != a[i])
{
printf("Wrong choice\n");
if (total == 1 || total == 0)
{
total=0;
}
else
{
total = total - 2;
}
}
}
}
printf("You have guessd the movie\n");
printf("The movie name is: ");
for (i = 0; i < 7; i++)
{
printf("%c",a[i]);
}
printf("Your score is %d\n",total);
}
This is the program output that I get each time I run the above code:
Enter your name:
raj
GUESS THE MOVIE GAME
_ _ _ _ M _ _
Let's begin the game
Enter character number 1
Wrong choice
Enter character number 1
I
Wrong choice
Enter character number 1
Wrong choice
Enter character number 1
Besides the deficiencies pointed out in comments, there's this major logic error:
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
…
}
}
If the loop encounters an m, it repeats endlessly. Eliminate the if (a[i] != 'm') or add an else ++i.

While loop using realloc, won't update arrays when printing

The code will not produce a compiler error, but i am trying to update the memory allocation after every loop if the user types Y, and increase the size of the memory. But after the first while loop, when i try to print the list of numbers using the first for loop, it will just show one number which will be 0.00000. I can't get it to update (which is what I am trying to do in the second if loop). Any help is appreciated.
#include<stdio.h>
#include<stdlib.h>
int main()
{
double *userNum = (double*)malloc(sizeof(double));
double sum = 0;
char userChar = 'Y';
int i = 0;
int j = 0;
if (userNum == NULL) {
printf("Error with memory");
return 1;
}
while (userChar == 'Y' || userChar == 'y') {
printf("Enter a number\n");
scanf("%lf", userNum);
printf("List of numbers:\n");
for (j; j < (i + 1); j++) {
printf( "%lf\n", userNum[j]);
}
printf("More numbers (Y/N)? \n");
getchar();
scanf("%c", &userChar);
if (userChar == 'Y' || userChar == 'y') {
userNum = realloc(userNum, (i + 2) * sizeof(double));
i++;
}
}
return 0;
)
You need to reinitialize your loop counter to 0 when printing out the numbers :
for (j = 0; j < (i + 1); j++) {
printf("%lf\n", userNum[j]);
}
And you need to increment the position in userNum that you scan the numbers into :
scanf("%lf", &userNum[i]);

realloc function don't save new elements with new values in c

function gets an array of grades and changes the amount of grades if there are less elements than before the function will delete those elements
for example: before: I entered in another function 3 grades: 100, 90, 80.
after: In this function it asked me to enter new amount, and I entered, and then entered it's grade, 70.
after I return it to the main and sending the array, grades, to a function which prints the array and it's stays with 3 elements, 100, 90, 80.
please help me i tried a lot of time and didn't succeed.
void changeNumOfGrades(int* grades, int size)
{
int numOfGrades = 0;
int i = 0;
do
{
if (i > ONE_ITERATION)
{
printf("Please enter positive number...\n");
}
printf("How many elements would you like? ");
scanf("%d", &numOfGrades);
i += 1;
} while (numOfGrades < 0);
grades = realloc(grades, numOfGrades*sizeof(int));
if (!grades)
{
printf("Unsuccessful realloc");
//There is no need to release memory because the realloc is for the same pointer.
}
if (numOfGrades > size)
{
printf("You have more grades than before,\nPlease enter their grades: \n");
int newGrade = 0;
//int newNumOfGrades = numOfGrades - size;
int i = 0;
for (i = size + 1; i <= numOfGrades; i++)
{
printf("Enter grade number %d: ", i);
scanf("%d", &newGrade);
*(grades + i - 1) = newGrade;
printf("hey %d", *(grades + 1));
}
}
}
In order for you to reallocate grades, you need to pass as **grades.
For test reasons, I have changed size to get the new allocation size, so you can print the array after the changeNumOfGrades
void changeNumOfGrades(int** grades, int *size/*get new size*/)
{
int numOfGrades = 0;
int i = 0;
do
{
if (i > ONE_ITERATION)
{
printf("Please enter positive number...\n");
}
printf("How many elements would you like? ");
scanf("%d", &numOfGrades);
i ++;
} while (numOfGrades < 0);
printf("%d",numOfGrades);
*grades = realloc(*grades, numOfGrades*sizeof(int));/*realloc **grade */
if (!grades)
{
printf("Unsuccessful realloc");
//There is no need to release memory because the realloc is for the same pointer.
}
printf("...\n");
if (numOfGrades > *size)
{
printf("You have more grades than before,\nPlease enter their grades: \n");
int newGrade = 0;
//int newNumOfGrades = numOfGrades - size;
int i = 0;
for (i = *size + 1; i <= numOfGrades; i++)
{
printf("Enter grade number %d: ", i);
scanf("%d", &newGrade);
*(*grades + i - 1) = newGrade;
//printf("hey %d", *(grades + 1));
}
}
*size = numOfGrades;/*get new size allocated*/
}
void main()
{
int numOfInts;
int *grades ;
grades = malloc(3*sizeof(int));
memset(grades,0,sizeof(int)*3);
grades[0]=100;
grades[1]=80;
grades[2]=20;
numOfInts = 3;/*initialize 3 items*/
changeNumOfGrades(&grades,&numOfInts);
printf("\n\n");
for (int i=0;i<numOfInts;i++)
{
printf("%d\n",grades[i]);
}
free(grades);
}

I am getting a _\377 in my output

I have a school assignment to make a hangman game. The game works how I want it to except for one small glitch. If the user entered word is 4 letters or less, the hidden word is displayed with an extra "_\377" at the end. When the user entered word is 5 letters or more, then there is no glitch. I am hoping that someone would be kind enough to help me trouble shoot the problem. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
if( string[i] == a)
{
val = 1;
}
i++;
}
if( val == 0)
{
return 100;
}
else
{
return i;
}
}
int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
outWord[i3] = '1';
i3++;
}
while(j2 < i2)
{
outWord[j2] = '-';
j2++;
}
puts(outWord);
while(gameover != 1 )
{
printf("What is your guess: ");
scanf("%s", &guess);
vari = 0;
if(letterfinder(inWord, guess, vari) == 100)
{
printf("Wrong!");
trys--;
printf("You have %d attempts left\n", trys);
if(trys == 0)
{
gameover = 1;
printf("You ran out of attempts. Game over\n");
}
}
else
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = (letterfinder(inWord, guess, vari));
while(letterfinder(inWord, guess, vari) != 100)
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = letterfinder(inWord, guess, vari);
}
puts(outWord);
}
int value = 0;
i3 = 0;
while( i3 <= i2)
{
if( outWord[i3] == '-')
{
value = 1;
}
i3++;
}
if(value != 1)
{
printf("Congratulations, you have guessed the word!\n");
gameover = 1;
}
}
return 0;
}
Your code has Undefined Behaviour. In the cases it "works" it is only by chance/luck. char guess; scanf("%s", &guess); That causes memory corruption as you are writing a string to a variable that can only hold a single char. Even a single letter guess will require two characters to store as all C strings are NUL terminated.
– kaylum

Program errors due to strcmp and strcpy in C

No matter how I edit my program there seems to be overflow errors and mismatching type errors. Can someone help me to make this run without errors.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int choice;
int i;
int j;
char type;
int amount;
int don_count = 0;
int req_count = 0;
int flag;
char donations_inv_type[100][20];
int donations_amount[100];
char requests_inv_type[100][20];
int req_amount[100];
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
scanf("%d", &choice);
while (choice != 5) {
if (choice == 1) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
printf("\nDonation Added!\n\n");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], type) == 0)
flag = i;
}
if (flag == -99) {
strcpy(donations_inv_type[i], type);
donations_amount[i] = amount;
don_count++;
}
else
donations_amount[flag] += amount;
printf("Donation Added!\n");
printf("Press any key to continue . . .\n\n");
}
else if (choice == 2) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
strcpy(requests_inv_type[req_count], type);
req_amount[req_count] = amount;
req_count++;
}
else if (choice == 3) {
printf("\n\n-------- Fulfilling Requests--------");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], requests_inv_type[0]) == 0)
flag = i;
}
if (flag == -99)
printf("Cannot be Fulfilled\n\n");
else if (donations_amount[flag] > req_amount[0]) {
donations_amount[flag] -= req_amount[0];
printf("Request Fulfilled");
req_amount[0] = 0;
}
else if (donations_amount[flag] == req_amount[0]) {
printf("Request Fulfilled");
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
}
don_count--;
for (i = flag; i < req_count; i++) {
strcpy(requests_inv_type[i], requests_inv_type[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
}
req_count--;
}
else if (donations_amount[flag] < req_amount[0]) {
printf("Partially Fulfilled");
req_amount[0] -= donations_amount[flag];
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
don_count--;
}
}
}
else if (choice == 4) {
printf("Printing the Donations Table\n\n");
for (i = 0; i < don_count; i++) {
printf("%s %d", donations_inv_type[i], donations_amount[i]);
}
printf("Printing the Requests Table\n\n");
for (i = 0; i < req_count; i++) {
printf("%s %d", requests_inv_type[i], req_amount[i]);
}
}
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
}
}
Any help is greatly appreciated and I would love an explanation as to what I did wrong so that I can learn and not make the same mistakes next time.
Declare type as character array.
char type[50];
Remove & in scanf(). You should not use & while reading string.
scanf("%s", &type); ==> scanf("%s", type);
^
Here you want to copy integers not strings
strcpy(donations_amount[i], donations_amount[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
Modify like this
donations_amount[i]=donations_amount[i + 1];
req_amount[i]= req_amount[i + 1];
Instead of char type you need char type[100]
Error in your code:
if (strcmp(donations_inv_type[i], type) == 0)
// ^^^^ should be char*
Note: Functions strcmp() and strcpy() should be passed \0 nul-terminated array of char (or say string).
Your scanf should look like scanf("%s", type);

Resources