Home > database >  In C, I'm struggling with Pointers
In C, I'm struggling with Pointers

Time:12-09

I have this code that I'm using for something else, but, boiled it down to the root problem I think. If I enter 5 for the scanf variable when I run it, the printf out is 0,16. I don't understand why this is giving me 16 for *pScores?

#include <stdio.h>

int main(void) {
  int a=0;
  int sum=0;
  scanf("%d",&a);
  int scores[a];
  int *pScores = &scores[0];
  printf("%d, %d\n",scores[0],*pScores);
}

CodePudding user response:

You are declaring an array

int scores[a];

and then printing out the value of scores[0] in two different ways. However, you have not stored anything into any of the elements of the scores array, so the values there are indeterminate.

Whether use of uninitialized (and therefore indeterminate) values in this way actually rises to the level of Undefined Behavior is a surprisingly deep and actually somewhat contentious question. (See the comment thread raging at the other answer.) Nevertheless, printing an uninitialized value like this isn't terribly useful. If you fill in a well-defined value to at least scores[0], I believe you'll find that both scores[0] and *pScores will print the same — that same — value.

Now, you might expect that the uninitialized value — whatever it is — would at least be consistent no matter how you print it (and I might agree with you), but when it comes to gray areas like this, and especially when a modern compiler starts leveraging every nuance of the rules in performing aggressive optimizations, the end results can be pretty surprising. When I tried your program, I got the same number printed twice (that is, I couldn't initially reproduce your result), but as suggested by Barmar in a comment, when I turned on optimization (with -O3), I started seeing conflicting results, also.

CodePudding user response:

You have undefined behavior, caused by reading a variable with automatic storage duration whose value is indeterminate.

In 6.2.4 Storage durations of objects one finds the following rule

For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration. If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.

Then in J.2 Undefined behavior:

The behavior is undefined in the following circumstances

...

  • The value of an object with automatic storage duration is used while it is indeterminate.

...

Among permitted very weird outcomes when dealing with indeterminate values is that they have a different value each time you read them. The Schroedinger wavefunction does not collapse!

  •  Tags:  
  • c
  • Related