I'm having a simple issue where my C executable is crashing after attempting to grab input from the user.
The idea of the program is to populate an array and eventually generate some data on that array. So far I have attempted to grab input from the user and immediately after the exe crashes. I've also edited the code temporarily whilst trying to debug what the issue is with no success. I have not touched c in a number of years and was very young when I had last and am quite a novice.
Can someone advise on any possible solution to why it would be crashing?
#include <stdio.h>
#include <stdbool.h>
double get_double(char prompt[50])
{
double tempDouble = 0;
printf("%s", prompt);
scanf("%d", tempDouble);
return tempDouble;
}
void populate_array(double *pData[])
{
int i = 0;
*pData[0] = get_double("Please Enter A Number : ");
//for(i = 0; i < sizeof(*pData); i++)
//{
//*pData[i] = get_double("Please Enter A Number : ");
//}
}
double get_sum(double data[10])
{
int i = 0;
double result = 0;
for (i = 0; i < sizeof(data); i++)
{
result += data[i];
}
return result;
}
int main()
{
//Variable Declarations
bool running = true;
bool playAgain = false;
double numbers[10];
double sum, min, max, var, dev;
//Process
populate_array(&numbers);
sum = get_sum(numbers);
printf("%d",sum);
}
void populate_array(double *pData[]) accepts an array of pointer, while you pass it just an array, it should be:
void populate_array(double pData[])
{
int i = 0;
pData[0] = get_double("Please Enter A Number : ");
}
Also, when you read the double, it should be:
// as proposed by Jonathan, the format string should contain '%lf' for double, I overlooked it.
scanf("%lf", &tempDouble);
if you pass scanf just tempDouble, it treats its value as an address, which is invalid address of course.
Your code contains:
scanf("%d", tempDouble);
You need to add & to the parameter you use in scanf().
And %d is used with integer. When you want to use double you need to use %lf; with a float, you'd use %f.
for (i = 0; i < sizeof(data); i++)
this will iterate after you reached the boundaries of the array.
for (i = 0; i < sizeof(data)/sizeof(double); i++)
this may be works but is not elegant
double get_sum(int numberOfElements, double data[10])
{
int i = 0;
double result = 0;
for (i = 0; i < numberOfElements; i++)
{
result += data[i];
}
return result;
}
this is the better approach
sum = get_sum(10, numbers);
In the main function call the get_sum function like this
Related
I'm trying to read from the keyboard until EOF, and insert each value into an array.
As simple as that sounds, for some reason, the elements don't get pushed into an array and I don't know why.
Can anybody help me understand what's going on?
Thanks.
void tipD(int dim)
{
long double distanta, timpOdihna;
long double distantaVec[100], timpOdihnaVec[100];
while (scanf("%Lf%Lf", &distanta, &timpOdihna) != EOF)
{
int i = 0;
distantaVec[i] = distanta;
timpOdihnaVec[i++] = timpOdihna;
}
for (int i = 0; i < dim; i++)
{
printf("%Lf %Lf\n", distantaVec[i], timpOdihnaVec[i]);
}
}
so I am working on my Binary adding program, but now I am stuck. I want to declare 2 variables for the first binary and second one, so I use the getBinary function I created to declare these 2. However, after I entered value for firstBin, I got the value I want, but after I entered the value for secBin, the value of firstBin somehow changes and become the same as secondBin. I was hoping for the variable to be unchangable. Thanks for the help
#include <stdio.h>
int * getBinary(){
int i;
int j;
static int first8bits[8];
for (i = 0; i != 8; i++){
printf("Input 8-bits Binary:");
scanf("%d",&first8bits[i]);
}
for (j = 0; j != 8; j++)
printf("%d",first8bits[j]);
printf("\n");
return first8bits;
}
int main(){
int o;
printf("Input the first Set of Binary...");
const int * firstBin = getBinary();
printf("Input the second Set of Binary...");
int * secBin = getBinary();
for (o = 0; o != 8; o++)
printf("%d",firstBin[o]);
}
Because of the static keyword.
Don't use static. Try:
int* first8bits = malloc(8 * sizeof(int));
This way you will allocate new memory each time you call it. You can still access it with the same [ i ] subscript. Remember to free the memory again at the end of main!
free(firstBin);
free(secBin);
I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}
I am having trouble with this code. In particular I can't seem to figure out why it is that the voteFractions() function doesn't work for me. It gets called appropriately, and all the correct parameters seem to reach the function, but I cannot get anything from "candidates[i].votes_fraction = candidates[i].votes/total;". All I ever get for candidates[i].votes_fraction is 0.00.
I tried running the program with NUMBER_OF_CANDIDATES = 1, and everything runs OK when that is the case, so I feel like I may be doing something silly, but I just can't seem to see it...
#define NUMBER_OF_CANDIDATES 10
typedef struct candidate{
char name[20];
int votes;
float votes_fraction;
} candidate;
int totalVotes(candidate *candidates)
{
int total = 0;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
total += candidates[i].votes;
return total;
}
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
candidates[i].votes_fraction = candidates[i].votes/total;
if (candidates[i].votes_fraction > most_votes)
{
most_votes = candidates[i].votes_fraction;
strcpy(winner, candidates[i].name);
}
}
}
int main()
{
candidate candidates[NUMBER_OF_CANDIDATES];
int total;
char winner[20];
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
printf("Enter candidate's name and the number of votes received: ");
scanf("%s %d", candidates[i].name, &candidates[i].votes);
}
total = totalVotes(candidates);
voteFractions(candidates, total, winner);
return 0;
}
The problem is that in this statement
candidates[i].votes_fraction = candidates[i].votes/total;
expression
candidates[i].votes/total
uses integer arithmetic because the both operands have type int. As total is always greater than or equal to candidates[i].votes then the result of the division is equal to 0. You have to write
( float )candidates[i].votes/total
Take into account that variable test is declared but not used in function voteFractions. You may remove it.
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
//...
I'm trying to complete the Project Euler problem found here. For some reason my function that determines whether or not a given string is a palindrome thinks "989010" is a palindrome. The funny thing is, if I directly enter that string into the palindrome function, it functions correctly. Here's my code (I'm a newb so sorry for the bad formatting!):
bool palindrome(char pal[]);
int main(){
int i = 0;
int j = 0;
int k = 0;
int numdig = 0;
int numtest = 0;
for(i = 999; i > 99; i--){
for(j = 999;j > 99; j--){ //for loops multiply all 3 digit numbers
k = i * j;
numtest = k;
numdig = 0; //this part takes care of determining the number of digits
while(numtest > 0){
numdig++;
numtest /= 10;
}
char string[numdig + 1];
itoa (k,string,10); //itoa turns an integer into a string w/ null char.
if( palindrome(string)){
printf("It is a palindrome: %i\n",k);
system("pause");
return 0;
}
}
}
return 0;
}
bool palindrome(char pal[]){
int half = (sizeof(pal) - 1)/2; //this divides the string in half
int forward = 0;
int backward = sizeof(pal)-2;
while(forward < half && backward > 0){ //compares the charactera in the front
if(pal[forward] == pal[backward]){ //to the chars in the back until they
forward++; //meet in the middle
backward--;
}
else{
return false;
}
}
return true;
}
The sizeof of the parameter is not the character count of the string pointed to, because the parameter, despite its declaration form, is merely a pointer but not an array. Use strlen instead and notice that it does not include the terminating \0 in its returned value (as opposed to sizeof when applied to a string array).
The string "989010" looks like a palindrome if you only take the first 3 characters of it, "989". Since sizeof applied to a pointer yields 4 on your machine, it's only those first three characters that are inspected.