Reputation: 159
I am very new to procedural programming, so I am not sure if my code is bad or if I am doing something wrong in Visual Studio.
So I have this bit of code that is supposed to print an integer, print it's location in memory, change it's value through memory and then print the new integer as well as it's location in memory.
It compiles and runs fine through the cmd with gcc, but not in Visual Studio.
#include <stdio.h>
int main(){
int a = 4;
printf("Integer is: %d\n", a);
printf("Integer is stored at: %p in memory\n", a);
int *pointer = &a;
*pointer = 3;
printf("Integer is now: %d at %p in memory\n",a,*pointer);
getchar();
return 0;
}
Visual studio gives me these errors when I try to compile and run:
line 9: error C2065: 'pointer' : undeclared identifier
line 9: error C2100: illegal indirection
line 11: error C2065: 'pointer' : undeclared identifier
line 11: error C2100: illegal indirection
Upvotes: 1
Views: 957
Reputation: 665
I think you should first declare the variables on top of the function,and when you print memory address with %p
you should give the address of the variable to be printed
try this
int main()
{
int a = 4;
int *pointer=&a;
printf("Integer is: %d\n", a);
printf("Integer is stored at: %p in memory\n",&a);
*pointer = 3;
printf("Integer is now: %d at %p in memory\n",a,pointer);
getchar();
return 0;
}
Upvotes: 2
Reputation: 36092
With VS2012 / C you need to add blocks in order to do what you want, unfortunately the compiler doesn't support declarations in the middle
int main(){
int a = 4;
printf("Integer is: %d\n", a);
printf("Integer is stored at: %p in memory\n", a);
{
int *pointer = &a;
*pointer = 3;
printf("Integer is now: %d at %p in memory\n",a,*pointer);
}
getchar();
return 0;
}
alternatively you can force to compile your .c file as a .cpp file by specifying the /TP
switch on the file.
Upvotes: 1
Reputation: 16315
The Visual Studio C compiler does not support C99, in particular being able to declare variables at any place in a block. GCC supports several revisions of the C language. IIRC, passing in -std=c89 as a flag to gcc will flag these also.
Upvotes: 5
Reputation: 16153
printf("Integer is stored at: %p in memory\n", a);
You need to take the address of a
as in &a
.
printf("Integer is now: %d at %p in memory\n",a,*pointer);
You need not dereference pointer
to get the address.
Use pointer
, not *pointer
If you're compiling with a C89 (I think) or older compiler, the declaration of pointer will have to be moved to the top of a block. You cannot declare variables in the middle of code in older C.
Upvotes: 1