Domanda

ho una preoccupazione per gli array a lunghezza variabile. Quando voglio allocare una matrice dinamica, vado a prendere nulla, se non è possibile allocare memoria sufficiente e posso rispondere a questo correttamente nel mio programma. Con una gamma di lunghezza variabile Non capisco queste informazioni. Cosa devo fare con questo?

È stato utile?

Soluzione

You are right that VLA's are basically always unsafe. The only exception is if you ensure that you never make them larger than a size you would feel safe making a fixed-size array, and in that case you might as well just use a fixed-size array. There is one obscure class of recursive algorithms where VLA's could make the difference between being unable to solve the problem (stack overflow) and being able to, but for the most part, I would recommend never using VLA's.

That doesn't mean VLA types are useless, though. While VLA is bad/dangerous, pointer-to-VLA types are extremely useful. They make it possible to have dynamically-allocated (via malloc) multi-dimensional arrays without doing the dimension arithmetic manually, as in:

size_t n;
double (*matrix)[n] = malloc(n * sizeof *matrix);

to get an n-by-n matrix addressable as matrix[i][j].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top