我是学习编程的新手,所以不要太苛刻。为什么我会收到此警告,又该如何解决?
这是完整的代码:
#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;
}
答案 0 :(得分:2)
警告应该认真对待,即使有时看起来似乎不必要,但这样做会养成良好的编程习惯,您可以初始化指向NULL
的指针,然后在需要时重新分配它:>
int *ptr_a = NULL;
然而,引发此问题的原因是您正在打印指针的值而不是其地址,这将是很好的,因为即使未初始化,它仍然具有地址,分配给指针时仅具有一个值。变量的地址或使其指向某个内存位置。
如果您要打印指针的地址,则需要&ptr_a
,并且我愿意承认,出于良好的考虑,我将其脚,将其强制转换为void*
,如%p
指定者所期望的那样指向void
而不是int
的指针:
printf("the address of the pointer is %p\n", (void*)&ptr_a);
答案 1 :(得分:2)
此行:
printf("the address of the pointer is %p\n", ptr_a); // this prints the address of the pointer
不打印指针的地址。它尝试打印ptr_a
的值。由于ptr_a
尚未初始化,因此编译器会警告您您未初始化使用它。
如果您使用以下方式打印了ptr_a
的地址:
printf("the address of the pointer is %p\n", (void *) &ptr_a);
然后,编译器将不警告使用,因为它不使用ptr_a
的值(未初始化),而仅使用其地址(在创建ptr_a
时设置的地址)。
在ptr_a = &a;
行之后,ptr_a
用一个值和这样的行初始化:
printf("The address of a is %p.\n", (void *) ptr_a);
将在没有编译器警告的情况下打印该值。