Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

declaring a variable-length array as a global variable in C

How is it possible to declare a variable-length array as a global variable ?

when variable length array is declared in a function before the length is scanned, it compiles but does not run. it gives segmentation fault. when the same declaration statement is shifted below the scanning statement, it runs fine.

in case we want a variable length array globally available to all functions, how can we do that? problem here is the that the length of the array can only be scanned through some function only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A variable length array (i.e. an array sized with a runtime value) can't be a global variable, because the expression you are using for the size must obviously be computed at compile time. It can only live on the stack. Presumably what you are getting is a static array with a size that depends on where in the code you are defining it (because you are redefining something it depends on).

Why can't you just use a global pointer and realloc() to size it as needed?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...