code not working and instead returning value 3221225477
Posted by Just_Big_5902@reddit | learnprogramming | View on Reddit | 7 comments
hello, i have a bunch of exercices to do in C, but somehow nothing i write works and i have no idea why. when i looked it up all i found was that it appears when you try to open u file that doesn't exist or using pointers that lead nowhere and i did neither. any help or hint would ne much appreciated
#include <math.h>
#include <stdio.h>
int a;
int b;
int main() {
scanf("%d",a);
scanf("%d",b);
/*if(b % 2 != 0){
printf("%f",a *( b-1) +a);
}
else{
if(b % 2 == 0 && b > 0) {
printf("%f\n",a *( b-1) +a);
}
}*/
return 0;
}
MeLittleThing@reddit
been a while, but
scanf()needs to store the values in a pointer. You're probably showing the memory address.scanf("%d", &a);and so onImmereally@reddit
Yup needs to be store in the address of a and b like above, your getting a trash value that was in that location.
I also don’t like the casting an int to a float in a print statement, I can’t remember if it would cause issues but it feels wrong.
Ngtuanvy@reddit
what compiler are you even using? Shouldn't it tell you that int is not compatible to void*?
HashDefTrueFalse@reddit
a and b are initialised to zero by the system and never change because scanf takes a pointer to the destination memory. Use the address of operator (&a, &b) to get the scanf args. %f is for floating point, use %d to interpret the bytes as what they are, a signed integer. The rest looks ok at a quick glance.
DevEmma1@reddit
You're passing a and b instead of their addresses to scanf(). Try:
Without the
&,scanfwrites to an invalid memory location, which commonly causes that exit code/crash.Dk000t@reddit
scanf() needs variable address to store data.
*Since a and b are integer, you should use %d in the printf().
Slottr@reddit
Use &a and &b instead
I think you need to read up on pointer values and how they reference within C