警告:指针在打印其地址时未初始化

时间:2020-09-21 20:19:33

标签: c

我是学习编程的新手,所以不要太苛刻。为什么我会收到此警告,又该如何解决?

这是完整的代码:

#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;
}

2 个答案:

答案 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);

将在没有编译器警告的情况下打印该值。