Inputted value not being written to arrray - c

I am working on what I thought would be a simple program to try and familiarize myself with C style code (vs. the C++ I'm used to), and have hit a roadblock.
I have allocated memory for an array using calloc, and want the user to simply enter a number, and have that number put into the array (this repeats until the array is fully populated). The array seems to have been created, but my code is not writing to the array. The program, when run, accepts an input, stores that input to a temporary variable,q (used for debugging purposes), but will not write the value of that temporary variable to the array.
Here is a snippet of code that I believe holds my issue:
//e is the size of array as indicated by user
values = (double *)calloc(e , sizeof(double));
double q = 0; // holds input just to make sure it works
for (int i = 0; i < e; i++)
{
printf("Please enter value %d: ",i+1);
scanf("%d", &q);
printf("%d", q); // confirms q = "input"
values[i] = q; //This isn't happening for me
}
I would really appreciate it if someone could please correct (and ideally explain) my error as to why values[i] is never equal to q.

The %d format specifier is for ints. For doubles use %lf with scanf and %f or %lf with printf.
scanf("%lf", &q);
printf("%f", q); // confirms q = "input"

Related

New to C; using arrays. Undesirable output

I'm new to C (programming in general). I was working on this for a while, my school assignment. I'm getting an output of many random numbers (e.g. 1xxxxxxxxx) instead of printed displays of input entered.
Here's the code in question:
#include<stdio.h>
int main()
{
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter item, price and quantity: ");
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
price[i] = ppu[i]*quantity[i];
total += price[i];
}
printf("ITEM\t\tPRICE PER UNIT\t\tQUANTITY\t\tPRICE\n");
for(i=0; i < 5; i++)
{
printf("%s\t\t%.2f\t\t%.0f\t\t%.2f\n", item[i], ppu[i], quantity[i], price[i]);
}
}
Change the format specifier to %lf. Don't forget to assign total with an initial value.
total hasn't been assigned (or initialized with) a relevant value.
Also, item[i] (a pointer to 20 chars) is converted to a pointer to char (what scanf expects) in the context of scanf. The & is wrong
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
// wrong ^^ ^^ ^
scanf("%s %lf %lf", item[i], &ppu[i], &quantity[i]); // thanks to Bpaul
Even better is making sure scanf did the right thing:
if (scanf("%s%lf%lf", item[i], &ppu[i], &quantity[i]) != 3) /* error */;
None of these variables and array members are initialized.
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
That means that they will contain random garbage values.
Now, the ones that you assign to with either scanf or the assignment operator will contain (possibly) useful data, but you are also missing out checking the return value of scanf, which will tell you how many values could be successfully read.
Also look at the way you use the 2-D array item. There is something wrong there.

Why does cmd crash when I run this code?

I am an absolute beginner in C, and I wrote this code in codeblocks and built it, it had no errors. The program is, we input two integers and display, sum, subtraction, multiplication, and division of no1 and no2.
Here's the code :
#include <stdio.h>
int main ()
{
int no1,no2,sum,sub,multi,div;
printf("Enter your first number");
scanf("%d", &no1);
printf("Enter second number");
scanf("%d", no2);
sum=(no1+no2);
sub=(no1-no2);
multi=(no1*no2);
div= (no1/no2);
printf ("%d + %d = %d \n",no1,no2,sum);
printf ("%d - %d = %d \n",no1,no2,sub);
printf ("%d * %d = %d \n",no1,no2,multi);
printf ("%d / %d = %d \n",no1,no2,div);
return 0 ;
}
I got 0 errors but when I ran it, cmd opens, and then I input values for no1 and no2 then the program crashes and gives the message windows will look into the issue.
Look closely at the this snippet: scanf("%d", no2);
Say you declare a variable named foo.
int foo;
This variable occupies some memory. It occupies four bytes of memory (because an int is four bytes wide).
Now let's declare another variable.
int *foo_ptr = &foo;
foo_ptr is declared as a pointer to int. We have initialized it to point to the foo variable.
As I said, foo occupies some memory. Its location in memory is called its address. The char '&' is the “address-of" operator.
This operator returns the address of an variable. In our case foo, thus foo_ptr now point to the address memory of the foo variable.
Think of every variable as a box. foo is a box that is sizeof(int) bytes in size. The location of this box is its address. When you access the address, you actually access the contents of the box it points to.
You missed '&' here...
printf("Enter second number");
scanf("%d", &no2);
You forgot to put '&' at the second scanf :)

What is the difference between printf("\ %d ",&t); and printf("%d ",t);

I was trying some C codes in Dev C++ and Visual C++.
For Example:
int t =6;
printf("\nt = %d ",&t);
The output is :
t = 2358848
why is it so ? How can I get the value of t?
&t gives you the address of t , not its value.
To print the value do:
printf("\nt = %d ", t);
The & is known as a unary, and it gives you the address of a variable. This gets confusing because when you use scanf, it wants an address to store the user input so it has you use a unary. But when printing, it wants the value to display it on screen, it doesn't care what its address is.
Example:
int t = 0;
scanf("%d", &t); // This saves what the user inputs to the memory location of t
printf("\n %d", t); // This prints the value the user input
Alternatively, if you actually want to see what an address is:
printf("\n %p", &t); // This displays a memory location properly formatted.
Try this: printf("\nt = %d ", t);
You are trying to print address of the t variable.

printf after scanf always displays 1 (same unexpected value)

Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.
int main(){
printf("Enter an integer: ");
int n = scanf_s("%d", &n);
printf("%d", n);
}
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened.
What you should do is
int numberOfItemsMatched;
int readValue;
numberOfItemsMatched = scanf_s("%d", &readValue);
if (numberOfItemsMatched == 1)
printf("%d\n", readValue);
I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
return type of scanf is number of items read. so if scanf is succesful in reading an item, it returns one which is assigned to n here. hence the output is 1. So separate declaration of n and scanf.

Adding numbers until a negative is encountered

I'm trying to create a program that lets the user enter numbers(maximum entries>10^6) until a negative is encountered. I've tried a lot of version but they either don't register that a negative value is entered or they crash.
This is where I'm currently at:
#include <stdio.h>
#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}
Your problem is on this line:
scanf("%i", entry);
Which should be:
scanf("%i", &entry);
You need to pass in the address of the integer variable that will store the scanned value. Since
entry was never initialized, it is just filled with garbage/whatever is in memory and not the entered value. See this reference, which states,
"Depending on the format string, the function may expect a sequence of additional arguments,
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"
You provide a way to leave if the entered number is too big:
while(i<HIGHEST){
But nothing to leave if it is less than 0; Try this:
while((i<HIGHEST)&&(i>=0)){
Additionally, #OldProgrammer is correct, your scanf() should be as he has pointed out.

Resources