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