I am trying to read the input from a keyboard which i will use to create a set of multiplications. If i hardcode the integer to use then the program works fine however when i let the user enter their own number the program crashes and shows an error about an access violation.
I'm sure this is something simple but as I am fairly new to C i'm not entirely sure of all the principles to follow when using the language.
#include <stdio.h>
#include <string.h>
#include <math.h>
void main()
{
int multiple = 0;
int i;
int answer;
printf("Enter the multiple you wish to use...");
scanf("%d", multiple);
printf("The multiplication table for %d is", multiple);
for(i = 开发者_Go百科1; i <= 10; i++)
{
answer = i * multiple;
printf("%d X %d = %d",i,multiple,answer);
printf("\n");
}
printf("Process completed.");
}
Note: I set the initial value of multiple to 0 otherwise i encounter an error when trying to use an uninitialised value.
scanf("%d", multiple);
should be:
scanf("%d", & multiple);
In other words, you need to give scanf a pointer to the thing you want to read into. This is a classic mistake in the use of scanf(), and one everyone makes from time to time, so remember this for the next time you make it :-)
Just to explain why this happened (as Neil already explained what was causing it), scanf was expecting an address to write to. When you passed in the value of 'multiple', it was interpreted as an address, specifically address 0 as that was the value at the time.
The reason for this is so that scanf can set the value of your variable to the value of the input. If you do not pass a pointer you are passing a copy of the value of the variable. When you pass a pointer you are passing a copy of the value of the pointer, so as long as scanf writes to that same memory address it can change the variable's value.
Change
scanf("%d", multiple);
to
scanf("%d", &multiple);
scanf
expects a pointer to the variable to set.
The correct form is
scanf("%d", &multiple);
You are not passing the address of variable for multiple to store the result from scanf
hence the requirement for scanf("%d", &multiple);
.
This is telling the runtime, to read an integer and place it into the address-of variable, hence &
must be used. Without it, you got a runtime error as you are passing the value of the variable but the runtime does not know what to do with it.
In a nut-shell, an address-of variable is indicated by &
.
Hope this helps, Best regards, Tom.
精彩评论