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