Read values into an array fails - c

I want to use a function to scanf up to 10 values for an array with the size 10, and also keep track of the number of values that are in the array because I'll need it later for solving some maths about the array, (max value, min value, etc.).
#include <stdio.h>
int enter(int MeasurmentData[], int nrOfmeasurments)
{
for(int i=0;i<10;++i)
{
int MeasurmentData[10];
scanf("%d",&MeasurmentData[i]);
int nrOfmeasurments = 0;
nrOfmeasurments ++;
return nrOfmeasurments;
}
int main()
{
int MeasurmentData[10];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n");
printf("v (View)\n");
printf("e (Enter)\n");
printf("c (Compute)\n");
printf("r (Reset)\n");
printf("q (Quit)\n");
printf("enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') \\ enter values
{
int MeasurmentData[10];
int nrOfmeasurments;
enter(MeasurmentData, nrOfmeasurments);
}
else if(menuoption == 'v') \\\ view values
{
//printf("%d", MeasurmentData[]);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
return 0;
}
}
}
When I run the program it should print Measurment tool 2.0, after the the user has the choice of inputting e(enter) which will scan in up to 10 values into an array, if the user clicks q(quit) while in the enter option already he will be returned to the main menu where he can do whatever.
V(view) prints out the array for the user so that he can view what elements are inside.
C(compute) uses the elements inside and the nr of elements to calculate the highest value element, lowest.

There are some errors in your code. Ill try to explain. You have over declared your variables too many times. And since you have a fixed loop you don't need to count the measurements you will always read 10 measurements.
Below are the code with some modifications. Feel free to ask anything about it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXIMUM_MEASURMENT 10
int enter(int MeasurmentData[])
{
char input[100];
int nrMeasurement = 0;
// reseting Measurment data
for(int i=0;i<MAXIMUM_MEASURMENT;++i) MeasurmentData[i] = 0;
for(int i=0;i<MAXIMUM_MEASURMENT;++i)
{
scanf("%99s", input);
if(strcmp(input, "q") == 0) {
break;
}
MeasurmentData[i] = (int) strtol(input, (char **)NULL, 10);
nrMeasurement++;
}
return nrMeasurement;
}
void showMeasurments(int* MeasurmentData, int length) {
int i = 0;
printf(" ======== Measurment ======== \n");
for(i = 0; i < length; i++) {
printf("%d ", MeasurmentData[i]);
}
printf("\n");
}
int main()
{
int MeasurmentData[MAXIMUM_MEASURMENT];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n" "v (View)\n" "e (Enter)\n" "c (Compute)\n" "r (Reset)\n" "q (Quit)\n enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') // enter values
{
enter(MeasurmentData);
}
else if(menuoption == 'v') // view values
{
// show
showMeasurments(MeasurmentData, MAXIMUM_MEASURMENT);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
return 0;
}
Edit: i have updated the code. So i have read the comments of your question and there you have explained a little better what you are trying to accomplish. So since you have the requirement to press 'q' to stop reading values. I have to read all measurments as string and convert to integer if it is not the character q.
Edit 2: Thanks to #user3629249 to point out some of the flaws from the code ill update with his suggestions.

Related

Declaration is not allowed on the initialization block part [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
#include <string.h>
#include <conio.h>
#include <math.h>
#include "helper2.h"
char validLoop = ' ';
int choice;
int validInput = 0;
main(){
repeat:
clrscr();
printf("=======================\nMenu\n=======================\n[1] Binary to Decimal\n[2] Sorting Algorithm(Ascending Descending)\n[3] Palindrome Checker\n=======================\n");
do{
printf("Enter Your Choice: ");
scanf("%d", &choice);
if (choice == 1 || choice == 2 || choice == 3){
validInput = 1;
}
else{
printf("Invalid Input! Please Input a value given within the choices.\n");
}
} while(validInput == 0);
if (choice == 1){
BinToDec();
}
if (choice == 2){
sorting();
}
if (choice == 3){
checker();
}
printf("\nPress Y||y to repeat or any key to exit.");
validLoop = getche();
if (validLoop == 'y' || validLoop == 'Y'){
goto repeat;
}
else{
return 0;
}
}
im getting errors on where my validLoop, choice, and validInput isnt being initialized and says "Declaration is not allowed here." it also says a statement is missing a ; on line 11. am i doing something wrong in my part?
edit: sorry, i forgot to add the header:
char checker(){
int i;
int check = 0;
char checker();
char word[50];
printf("Insert a string: ");
scanf("%s", &word);
for (i=0;i<strlen(word)/2;i++){
if (word[i] == word[strlen(word)-i-1]){
check++;
}
}
if (check == strlen(word)/2){
printf("%s is a palindrome", word);
}
else{
printf("%s is not a palindrome", word);
}
return 0;
}
int BinToDec(){
char binary[8];
int i;
int sum=0;
int value;
int length;
printf("Input binary number you want to convert to decimal: ");
scanf("%s", binary);
length = strlen(binary);
for (i=strlen(binary)-1;i>=0;i--){
value = length - (i + 1);
if ((int)binary[i]-48 == 1){
sum = sum + pow(2.0, (float)value);
}
}
printf("%d", sum);
getch();
return 0;
}
int sorting(){
int i;
int sort[10];
int min;
int temp;
int currentElement;
int compareElement;
printf("Input integers to sort: ");
for (i=0;i<10;i++){
scanf("%d", &sort[i]);
for (currentElement=0;currentElement<(sizeof(sort)/sizeof(sort[0]))-1;currentElement++){
min = currentElement;
for (compareElement=currentElement+1;compareElement<(sizeof(sort)/sizeof(sort[0]))-1;compareElement++){
if (sort[compareElement] < sort[currentElement]){
min = compareElement;
}
}
temp = sort[currentElement];
sort[currentElement] = sort[min];
sort[min] = temp;
}
printf("Ascending Order: ");
for (currentElement=0;currentElement<=(sizeof(sort)/sizeof(sort[0]))-1;currentElement++){
printf("%d, ", sort[currentElement]);
}
printf("\n");
printf("Descending Order: ");
for (currentElement=(sizeof(sort)/sizeof(sort[0]))-1;currentElement>=0;currentElement--){
printf("%d, ", sort[currentElement]);
}
printf("\n");
return 0;
}
basically the whole this is supposed to be a program to call my functions from the header file. everything was smooth sailing and it was even working before i tried adding validations on my part. i dont know if this really helps but i would appreciate every feedback with this. im using a turbo c emulator as my compiler and working environment.
printf("Input integers to sort: ");
for (i=0;i<10;i++){
scanf("%d", &sort[i]);
Seems closing } is missing. Writing actual definitions in header is not a good habit.
Other coding issues aside.
In the code that you show is in your header file you have the following line:
char checker();
within function char checker() I suspect that this is your culprit.

Function Crashes Main After Finishing Execution - C

I made this simple program that asks the user to input the number of columns the matrix called arp is going to have because, that way when the program asks the user to input a number so it can find matches on the numbers stored at the array without comparing all 10 columns allocated on memory with array to pointer type.
The problem here comes when the user inputs into the columns size definition 2. All works fine before the last function of p3() does its job, then it doesn't even return to main to execute the infinite loop defined there. I have tried removing the pointers and didn't work; I also tried removing other parts of the code but still nothing...
Update: Tried removing the function to find elements felmnt() and still the same.
Here is The Buggy Code:
#include <stdio.h>
#include <stdlib.h>
int loop = 1;
void keepalive(void)
{
int ckr = 0;
fflush(stdin);
printf("\n\n ******[s]<< CONTINUE | EXIT >>[n]******\n");
while(printf(" > ") && (ckr = getchar()) != 's' && ckr != 'n') fflush(stdin);
getchar();
if(ckr == 'n') loop = 0;
system("CLS");
}
void felmnt(int *colu, int (*arp)[10])
{
int nius=0, colmts, x, i, ejct;
do
{ // loop to let the user find more elements inside matrix
colmts=0;
printf("\n Insert The Number To Find\n > ");
scanf("%d", &nius);
for(x=0; x<*colu; x++) // search of element inside matrix
{
for(i=0; i<=9; i++)
if(nius == arp[i][x])
colmts++;
}
if(colmts>1) // results printing
{
printf("\n %d Elements Found", colmts);
}else if(colmts)
{
printf("\n 1 Element Found");
}else
{
printf("\n Not Found");
}
printf("\n TRY AGAIN? s/n\n > ");
ejct=getchar();
getchar();
}while(ejct=='s');
}
void mat(int *colu, int (*arp)[10])
{
int ci, cn, tst=0;
for(ci=0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++)
{
printf("\n Input The Number [%d][%d]\n > ", ci+1, cn+1);
scanf(" %d", &arp[cn][ci]);
}
}
printf(" Numbers Inside Matrix> ");
for(ci = 0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++) printf(" %d", arp[cn][ci]);
}
}
void p3(void)
{ // >>>>main<<<<
int colu=0;
while(loop)
{
printf("\n Input The Quantity Of Columns To Use\n > ");
scanf("%d", &colu);
int arp[10][colu];
mat(&colu, arp);
felmnt(&colu, arp);
keepalive();
}
}
int main(void)
{
int ck = 0, ndx;
while(1)
{ // infinite loop
p3();
fflush(stdin);
printf("\nPause !!!");
getchar();
}
return 0;
}

C Outputting array from another function

I am trying to copy the array winner from my function 'enter', so that i am able to just output it on the 'previous' function. When picking the option for the previous option I have gotten nothing outputting. Its only the last function named 'previous' that is not working, but to produce the problem the majority of the code is needed.
#include <stdio.h>
#include <string.h>
char enter(char names[][20]);
void menu();
void previous(char winner[][8]);
int main()
{
char names[16][20];
int i;
printf("Please enter the names of the players:\n");
/*Making the user enter 16 times*/
for (i = 0; i < 16; i++)
{
scanf("%9s", &names[i]);
fflush(stdin);
}
/*Clearing Screen*/
system("cls");
menu(names);
return names[16][20];
}
void menu(char names[][20], char winner[][8])
{
int choice;
printf("Please select one of the following options:\n\n"
"Press 1 to enter game results\n"
"Press 2 to display the current round\n"
"Press 3 to display the players advancing to the next round\n"
"Press 4 to display the previous round\n"
"Press 5 to exit the program\n");
scanf("%d", &choice);
if(choice == 1)
{
enter(names);
}
system("cls");
if(choice == 3)
{
previous(winner);
}
}
char enter(char names[][20])
{
int result;
int score1;
int score2;
int p, c, j, l, i;
char winner[8][8];
system("cls");
for(i = 0; i < 8; i++)
{
printf("\n\n%s vs %s",names[i],names[i+8]);
score1 = 0;
score2 = 0;
for(j = 0; j < 5; j++)
{
printf("\n\nEnter game %d results, press 1 if %s won or"
" 2 if %s won :\n",(j+1), names[i], names[i+8]);
scanf("%d", &result);
if(result == 1)
{
score1++;
}
if(result == 2)
{
score2++;
}
printf("\n\n1Current score is %d-%d", score1, score2);
if(score1 == 3)
{
printf("\n\n%s adavances to the next round!",names[i]);
strncpy(winner[i], names[i], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
if(score2 == 3)
{
printf("\n\n%s adavances to the next round!",names[i+8]);
strncpy(winner[i], names[i+8], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
}
}
system("cls");
printf("The players advancing to the next round are:\n\n");
for(p = 0; p < 8; p++)
{
for(c = 0; c < 8; c++)
{
printf("%c",winner[p][c]);
}
printf("\n");
}
printf("\n\nPress Enter to Continue");
getch();
system("cls");
menu(names, winner);
return winner[8][8];
}
void previous(char winner[][8])
{
int i, j;
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
printf("%c",winner[i][j]);
}
printf("\n");
}
}
There is no data for the array winner in your program! At least not when you call it for the first time.
The signature for the menu function is:
void menu(char names[][20], char winner[][8]);
but you call it from main like this:
menu(names);
The winner parameter is missing. This shouldn't happen, but you have declared a prototype for this function, namely:
void menu();
Unfortunately, C treats the empty parens as meaning "whatever parameters you pass", not as function that takes no parameters. That means that your function call slips by. The fix is to provide the correct signature for the prototype and also to pass a suitable winner array from main.
Strangely, your enter function provides a local array winner. This array will always be a new array when you call enter. That's probably not what you want. As is, your program should have one names and one winner array. (You can pass these arrays around, but you should make sure that tese arrays are consistent. Don't create new arrays when you really want to operate on existing ones.)
You also call your menu recursively. That means the you go ever deeper into the call structure without real benefit. Dont do that; use a loop instead: do display the menu while the user hasn't chosen "quit". (There are applications for recursive functions, but this isn't one.)

Segmentation fault in C? Arrays, pointers, functions

Hi due to my lack of knowledge in C (second year in college). Compiler ate my code and built the app. But after accepting first value - numOfIntegers it stops working and debugging tells that the segmentation has been failed. SIGSEGV.
How to fix that?
There is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* -----------------------------------------
Program: Question 1
Author: Maggot #9
Email: maggot99999#gmail.com
ID: B00076450
Date: 16 September 2015
Purpose: Who knows?
------------------------------------------ */
void wait(int);
void controlMenu(int, int[]);
int sumOfIntegers(int, int[]);
int avgOfIntegers(int, int[]);
int prodOfIntegers(int, int[]);
int minInteger(int, int[]);
int maxInteger(int, int[]);
const char * getName (int value)
{
static char * arrayName[] = {"first","second","third", "fourth",
"fifth","sixth", "seventh", "eighth", "ninth", "tenth"};
static char badValue[] = "unknown";
if (value<10 && value>=0)
return arrayName[value];
else
return badValue;
}
int getValue(int numOfInteger)
{
int value;
wait(100);
printf("Please enter %s the value:", getName(numOfInteger));
scanf("%d",&value);
return value;
}
void prepare(int * numOfIntegers)
{
wait(300);
printf("Hey again that C stupid lang\n\n");
wait(200);
printf("Please enter how many values you want to put: ");
scanf("%d",numOfIntegers);
return;
}
void initialize(int numOfIntegers,int* arrayNum[])
{
int i;
for(i=0; i<(numOfIntegers); i++)
arrayNum[i] = getValue(i);
wait(500);
printf("\nPlease enter press any button to continue");
wait(100);
getch();
wait(600);
system("cls");
wait(200);
return;
}
int main()
{
int numOfIntegers;
prepare(&numOfIntegers);
int arrayNum[numOfIntegers];
initialize(numOfIntegers, &arrayNum[numOfIntegers]);
controlMenu(numOfIntegers, &arrayNum[numOfIntegers]);
return 0;
}
void controlMenu(int numOfIntegers, int arrayNum[])
{
int i;
char chooseNum;
printf("Please choose any of the following:\n\n1. The integers accepted\n2. The sum of the integers\n3. The average of the integers\n4. The product of the integers\n5. The smallest integer\n6. The largest integer\n0. Exit menu\n");
while(1)
{
chooseNum = getch();
switch(chooseNum)
{
case '0':
return;
case '1':
printf("\n>>> The integers are:");
for(i=0; i<(numOfIntegers); i++)
{
printf("\n>>> The %s is %d", getName((i+1)), arrayNum[i]);
}
break;
case '2':
printf("\n>>> The sum of integers is: %d", sumOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '3':
printf("\n>>> The average of integers is: %d", avgOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '4':
printf("\n>>> The product of integers is: %d", prodOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '5':
printf("\n>>> The smallest integer is: %d", minInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '6':
printf("\n>>> The largest integer is: %d", maxInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
default:
break;
}
printf("\n\n");
}
}
int sumOfIntegers(int numOfIntegers,int arrayNum[])
{
int sum=0;
for(int i=0; i<(numOfIntegers); i++)
sum += arrayNum[i];
return sum;
}
int avgOfIntegers(int numOfIntegers, int arrayNum[])
{
int average=0;
average = sumOfIntegers(numOfIntegers, arrayNum[numOfIntegers])/numOfIntegers;
return average;
}
int prodOfIntegers(int numOfIntegers, int arrayNum[])
{
int i,product=0;
for(i=0; i<(numOfIntegers); i++)
product *= arrayNum[i];
return product;
}
int minInteger(int numOfIntegers, int arrayNum[])
{
int i,smallest=0;
smallest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(smallest>arrayNum[i])
smallest=arrayNum[i];
else
continue;
}
return smallest;
}
int maxInteger(int numOfIntegers, int arrayNum[])
{
int i,largest=0;
largest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(largest<arrayNum[i])
largest=arrayNum[i];
else
continue;
}
return largest;
}
void wait(int ms)
{
Sleep(ms);
return;
}
I can see this fault in getName() which will access memory beyond the array bounds
if (value>10 || value<1)
return arrayName[value];
I believe you are using the wrong test, try
if (value <= 10 && value > 0)
return arrayName[value-1];
assuming value is in the range 1..10 as the textual array implies.
2) a fault in GetValue where you input into numOfInteger but return value, which is uninitialised.
3) in prepare the statement
scanf("%d",&numOfIntegers);
will not pass the input value back to the caller. You should have either passed a pointer to the variable, or returned the value input.
But there might be a lot else wrong. Build your program step by step, checking and trying to break it as you go (with absurd input). Pay attention to compiler warnings - the second fault I listed will generate one.
EDIT okay... let's examine function prepare which after removing noise is
void prepare(int numOfIntegers)
{
scanf("%d",&numOfIntegers);
return;
}
This inputs a value to the function parameter that was passed. This is legal, since you can use a function argument in the same way you can a local variable (perhaps subject to const qualification).
Although it's not a coding error, it does not achieve anything. 1) you usually pass an argument like this to be used by the function in some way, perhaps in its limits and/or in its prompt. 2) Altering the argument like this will not find its way back to the caller.
Here are two ways to deal with this.
A) the function returns the input value
int prepare(void)
{
int value;
scanf("%d", &value); // the address of value
return value;
}
...
int input = prepare();
printf("%d\n", input);
B) the function takes a pointer argument
void prepare(int *value)
{
scanf("%d", value); // value is already a pointer
}
...
int input;
prepare(&input);
printf("%d\n", input);

C programming: Input is assigned but output display shows the incorrect value

I have been trying to figure out why my code isn't working properly. I know my code below is a mess (I am a rather poor C programmer thus far). Its a work in progress. Specifically
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
I find that when i run my program I might select a keyboard input of 1, meaning I am looking at my second record in my file entries.txt. The printout of vIndex however is a number much much larger, much likely the last information stored there. Running in debug however, i find that vIndex change to 1 and but prints the strange number. My entire code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec
{
int i;
float PI;
char A;
} Record;
typedef struct
{
char fname[20];
char lname[50];
char phone[15];
} Contact;
Record * arrayAlloc(int size);
char * stringAlloc(int size);
Contact * contactAlloc();
void structAlloc();
int main(void)
{
int *ptrInt;
Record * ptrRec;
int i = 0;
char * myName;
Contact * contacts;
ptrInt = (int *)malloc(sizeof(int));
int vIndex=0;
int displayMenu();
Contact * contactAlloc();
// void searchIndex();
void searchFirst();
void searchLast();
void searchPhone();
contacts = contactAlloc();
char choice;
choice = displayMenu();
while (choice !=5)\
{
if (choice == 1)
// searchIndex();
{
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
// fgets(vIndex, 700, stdin);
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. \nPhone Number:\t%c.\n\n ", &vIndex, contacts[vIndex].fname, contacts[vIndex].lname, contacts[vIndex].phone);
}
else if (choice == 2)
searchFirst();
else if (choice == 3)
searchLast();
else if (choice == 4)
searchPhone();
choice = displayMenu();
}
printf("Thank for you using this program.\n");
return 0;
}
int displayMenu()
{
int choice = 0;
while (choice!= 1 && choice != 2 && choice != 3 && choice != 4 && choice!=5)
{
printf("\nWelcome to the phone book application. Please choose from the following options:");
printf("\n\n\t 1) Search the phone book by index. \n\t 2) Search the phone book by first name. \n\t 3) Search the phone book by last name. \n\t 4) Search the phone book by phone number. \n\t 5) Quit.\n\n");
scanf("%d", &choice);
}
return choice;
}
Contact * contactAlloc()
{
FILE * fin;
int count = 0, i = 0;
char aLine[100];
Contact * ptrContact;
fin = fopen("entries.txt", "r");
if (fin != NULL)
{
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
count++;
}
fseek(fin, 0L, SEEK_SET);
count = count / 3;
ptrContact = (Contact *) calloc(count, sizeof(Contact));
count = 0;
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
if (aLine[strlen(aLine) - 1] == '\n')
{
aLine[strlen(aLine) - 1] = '\0';
}
if (i % 3 == 0)
{
strcpy(ptrContact[count].lname, aLine);
}
else if (i % 3 == 1)
{
strcpy(ptrContact[count].fname, aLine);
}
else if (i % 3 == 2)
{
strcpy(ptrContact[count].phone, aLine);
//printf("Line %d at count %d: %s\n", i, count, aLine);
count++;
}
i++;
}
//count=count*3;
printf("%d contacts loaded.\n\n", count);
fclose(fin);
}
return ptrContact;
}
/*
void searchIndex()
{
int vIndex=0;
printf("Please enter the index of the contact you wish to view. This should be a positive integer");
scanf("%d", &vIndex);
fgetc(stdin);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. Phone Number:\t%c.\n\n ", &vIndex, &Contact[vIndex].fname, &Contact[vIndex].lname, &Contact[vIndex].phone);
}
*/
void searchFirst()
{
}
void searchLast()
{
}
void searchPhone()
{
}
You are printing the address of vIndex instead of the value:
printf("The value of vIndex is %d", &vIndex);
Change this line to the following:
printf("The value of vIndex is %d", vIndex);

Resources