Declaring a pointer without initializing

Walkbitterwyrm Lightwarg 20 Reputation points
2023-09-03T21:48:51.2566667+00:00

I want to know whether is it okay to declare a pointer without initializing?

#include <stdio.h>

int main()
{
    int i, *ptr_i; // Is this okay to declare a pointer without initializing?
    int a, *ptr_a = 0;

    i = 1;
    a = 2;

    ptr_i = &i;
    ptr_a = &a;

    printf("The values of i and a are %d and %d", *ptr_i, *ptr_a);

    return 0;
}

In the above program, pointer ptr_i is not initialized but ptr_a is. But still the program runs without errors and warning. So is it necessary to initialize a pointer at the time of declaration?

Developer technologies C++
Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2023-09-04T01:55:44.2333333+00:00

    Hi,Walkbitterwyrm Lightwarg

    is it okay to declare a pointer without initializing?

    You can declare a pointer without initializing it. But it is recommended using initializationint* ptr_i = NULL;
    so that you can check if the variable has been initialized.

    if (ptr_i != NULL)
     {
         //do something
     }
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. WayneAKing 4,931 Reputation points
    2023-09-04T03:03:22.51+00:00

    It may be worth noting that variables that aren't given an explicit initial value may be default initialized.

    Global variables and static local variables are default initialized to zero.

    Non-static local variables are not default initialized. However, some compilers such as Visual Studio may give them a specific initial value in Debug builds to assist in the debugging process.

    #include <stdio.h>

    int g1, *gp1; // default initialized to zero

    int main()

    #include <stdio.h>
    
    int g1, *gp1; // default initialized to zero
    
    int main()
    {
    
        static int sn, *snp; // default initialized to zero
        int n1, *np1; // not default initialized, contents indeterminate
    
        printf("g1 = %d\tgp1 = %p\n", g1, gp1); // g1 = 0  gp1 = 00000000
    
        printf("sn = %d\tsnp = %p\n", sn, snp); // sn = 0  snp = 00000000
    
        //printf("n1 = %d\tnp1 = %p\n", n1, np1); // gives compiler errors
    
        return 0;
    
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.