How does the working of compiler differs in both cases although in both cases, n is unknown to compiler during compile time? [closed]

StackOverflow https://stackoverflow.com/questions/16242504

  •  13-04-2022
  •  | 
  •  

문제

Code 1:

int n;
int c[n];
scanf("%d",&n);

Code 2:

int n;
scanf("%d",&n);
int c[n];

The first one gives segmentation fault but second one works fine.

도움이 되었습니까?

해결책

Since both code segments use an uninitialized variable, they invoke undefined behavior (Not to mention that you are passing in an int where you should be passing in an int*. With undefined behavior the compiler makes no guarantees about what will happen. It could crash as in the first case, produce no error in the second case, or make demons fly out your nose.

What's happening is that in once case n has a value that happens to be set to a writable address and in the other it doesn't.

다른 팁

int n;     // n is uninitialized
int c[n];  // you're trying to declare an aray with an uninitialized value
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top