Reputation: 13
I'm new to learning programming by the way so don't be too harsh. Why exactly am I getting this warning and how do I fix it?
Here's the full code:
#include <stdio.h>
int main()
{
int a; // this declares the 'a' variable
int *ptr_a; // this declares the pointer variable
printf("a:");
scanf("%d", &a);
printf("a is %d\n", a); // this prints the value of 'a' that is read from the keyboard
printf("the address of the pointer is %p\n", ptr_a); // this prints the address of the pointer
ptr_a = &a; // this points the pointer to the 'a' variable
*ptr_a = *ptr_a + 5; // this modifies the 'a' variable with its pointer
printf("the value of the modified a is %d\n", a); // this prints the modified value of 'a'
printf("the address of the modified pointer is %p\n", ptr_a); // this prints the modified address of the pointer
return 0;
}
Upvotes: 1
Views: 140
Reputation: 23802
The warnings are to take seriously, even though they may seem unnecessary at times, doing so will create good programming habits, you can initialize the pointer to NULL
then reassign it later, when you need to:
int *ptr_a = NULL;
However what's triggering the problem here is the fact that you are printing the value of the pointer not its address, which would be perfectly fine as it still has an address even when uninitialized, it only has a value when you assign it the address of a variable or otherwise make it point to some memory location.
If you want to print the address of the pointer you'll need &ptr_a
and for good measure, being pedantic I'll admit, cast it to void*
as %p
specifier expects a pointer to void
, not to int
:
printf("the address of the pointer is %p\n", (void*)&ptr_a);
Upvotes: 2
Reputation: 222536
This line:
printf("the address of the pointer is %p\n", ptr_a); // this prints the address of the pointer
does not print the address of the pointer. It attempts to print the value of ptr_a
. Since ptr_a
has not been initialized, the compiler warns you that you are using it uninitialized.
If you printed the address of ptr_a
, with:
printf("the address of the pointer is %p\n", (void *) &ptr_a);
Then the compiler will not warn use, because this does not use the value of ptr_a
(which is not initialized), just its address (which is set when ptr_a
is created).
After the line ptr_a = &a;
, ptr_a
is initialized with a value, and a line like this:
printf("The address of a is %p.\n", (void *) ptr_a);
will print the value without a compiler warning.
Upvotes: 2