Question

For this part I actually just need to scanf a value into a variable and then put it into an equation to spit out a number.

Analogue input (-5V to 5V):
1
e is -1073750280

the code:

printf("Analogue input (-5V -5V):\n");
scanf("%d",e);
printf("e is: %d \n", e);

The number that e prints out as changes every time I run the program. I figure it has to do with memory but I cannot figure out what.

these are the variable declarations:

uint16_t *pointer;
int e,d,i;
Was it helpful?

Solution

C passes all of its function parameters by value, not by reference. That means functions cannot modify their parameters directly:

void NoChange(int i) {
  printf("Before: %d\n", i);
  i = 10;  // Changes only the local copy of the variable.
  printf("After: %d\n", i);
}
main() {
  int n = 1;
  printf("Start: %d\n", n);
  NoChange(n);
  printf("End: %d\n", n);
}

Output:

Start: 1
Before: 1
After: 10
End: 1

If you want a function to change the contents of a variable, you need to pass its address. Then the function can modify the data at that address, which effectively modifies the variable:

void Change(int *i) {
  printf("Before: %d\n", *i);
  *i = 10;  // Changes the memory that i points to.
  printf("After: %d\n", *i);
}
main() {
  int n = 1;
  printf("Start: %d\n", n);
  Change(n);
  printf("End: %d\n", n);
}

Output:

Start: 1
Before: 1
After: 10
End: 10

So in order for the scanf() function to store data in a variable, you need to pass it the address of that variable, like this:

int e;
scanf("%d", &e);

OTHER TIPS

scanf("%d", &e); is the correct answer as others have pointed out. The scanf function needs a pointer to where you want it to store the data, otherwise it doesn't know where your variable is.

Since scanf was expecting a pointer it converted the uninitialized value stored inside e to a pointer and stored the result there. This is undefined behaviour, a phrase you will see in the C/C++ section a lot, and you shouldn't do it.

Also, since scanf did nothing to your variable, printf was printing the uninitialized value of e, which is why you were getting the unexpected result.

scanf("%d",&e);

You are missing &.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top