Table declaration in a function
source link: https://www.codesd.com/item/table-declaration-in-a-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Table declaration in a function
Is it safe to write code like below?
void func(int v[], int size) {
int array_local[size];
for(int i = 0; i < size; i++) array_local[i] = v[i];
/*
Other stuff...
*/
}
Or could I stumble upon some kind of error?
Yeah this is perfectly fine and valid on and above C99
. It is called VLA.
To be on safer side, you should put a check on the value of size
before using it as the number of elements of the array. As you've got the size
defined as int
, you should prohibit passing a value of say -5
to size
.
That said, for the remaining part of the code (as a general suggestion)
v[i]
should not cause in memory overrun.- The array is local to the function. You should never try returning the address of the array (Either through a pointer or through
return
statement).
Related Articles
Using a table declared in a function to another function
C ++ - Declaration of internal functions of tables
How do I include a Temp table in a SQL function
Does the symbol table for C ++ contain function names and class names?
Drop a temporary table when leaving a function
How to delete everything from a database (tables, views, stored procedures, functions)?
Update the table in a complex function using exceptions
PostgreSQL - equivalent version of a table declared in MySQL?
Why is a function declaration in another function compiled and what does it do?
How to pass parameters to a function declared as left = function ()
In php, how can I make sure that the static variables declared in a function will not be restarted each time the function is called?
Why can not models be declared in a function?
How to declare a model function taking a model template parameter with a type of known model argument?
using nhibernate t-sql table-valued user-defined functions
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK