Reputation: 11
I finished three programs today, I am a student and I tend to overthink I can do more than I did. The problem is when I input 3 numbers, shouldn't there be three memory addresses? I feel like my program is missing a component that moves the pointer. The code is provided below. Why in our career would memory address be used?
#include <stdio.h>
#include <stdlib.h>
void options()
{
puts("\t\t\tMain Menu");
puts("\t\ta. Enter New Integer Value");
puts("\t\tb. Print Pointer Address");
puts("\t\tc. Print Integer Address");
puts("\t\td. Print Integer Value");
puts("\t\te. Exit");
puts(" \tPlease enter an option from the menu: ");
}//end options
int main(void) {
//Intialize and Declare variables
char menuOption;
char valueStr [50];
int i;
int *iPtr= NULL;
while(menuOption != 'e')
{
//Four Menu Options
options();
menuOption = getc(stdin);
getc(stdin);
switch(menuOption){
case 'a':
//Enter New Integer Value
printf("Enter an Integer: ");
gets(valueStr);
i = atoi(valueStr);
break;
case 'b':
//Print Pointer Address
iPtr = &i;
printf("Address of Pointer is %p\n", (void *) iPtr);
break;
case'c':
//Print Integer Address
printf("Address of integer is %p\n", (void *) &i);
break;
case'd':
//Print Integer Value
printf("The integer value is %d\n", i);
break;
case'e':
break;
default:
printf("Invalid Option, try again\n");
break;
}//end Switch Statement
}//end while statement
return 0;
}
Upvotes: 0
Views: 559
Reputation: 58825
The variable i
is always at the same location in memory throughout the execution of main
, so no matter how many times you print its address, you'll see the same value. That's an important property of the way pointers work in C: any given variable keeps the same address throughout its lifetime. If this were not true, then pointers would be impossible to use reliably, because even if the pointer stayed the same, you'd have no way of knowing if the variable had moved out from under it.
When the loop iterates for a second time, assigning to i
overwrites the previous value at that location with the new value. It doesn't allocate a separate location for it, if that's what you were thinking. Besides violating the above rule, that would also mean that any significant loop would run you out of memory almost immediately.
Upvotes: 1