Search code examples
cpointersstructcompiler-errorsinitialization

Compilation error - Variable pointer is uninitialized when used here


#include <stdio.h>

#define LENGTH_OF_A_MACRO    5

struct structS{
    unsigned int scgsToTrace[LENGTH_OF_A_MACRO];
    unsigned int noOfScgsToTrace;
} structS;

int main()
{
  unsigned int scgsToTrace[LENGTH_OF_A_MACRO] = {0};
  unsigned int noOfScgToTrace = 0;

  structS* commonData_p;
  noOfScgToTrace = commonData_p->noOfScgsToTrace; //Q1: Compilation Error

  for (unsigned int i = 0; i < noOfScgToTrace; i++) //Q2: noOfScgToTrace garbage value?
  {
    unsigned int scgToTrace = scgsToTrace[i];
    ...............................
   }
   return 0;
}

I am trying to assign noOfScgsToTrace from the structS using a pointer variable commonData_p. But i am getting a compilation error here saying variable "commonData_p" is uninitialized when used here as mentioned near the comment above. Should i initialize it explicitly? and How? I have two questions here

Question 1: Why is it saying uninitialized here? Question 2: By initiliazing noOfScgToTrace as 0 does it consider the value as garbage value in the for loop if it doesn't assign properly?

Any help is really appreciated. Thanks in Advance!


Solution

  • You forgot to name the type of commonData_p which is why you get a compilation error. You also forgot to initialize it:

    struct structS* commonData_p = &structS; // note "struct structS"
    

    Demo

    Note:

    Your noOfScgToTrace = commonData_p->noOfScgsToTrace; is fine because the global structS is automatically initialized (to zero) but had you moved the declaration into a function, like main, it had been uninitialized and reading it would then make your program have undefined behavior.