mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
Edit variable-length array example
The current example seems to be trying to set a size for a char buffer, use fgets to populate that buffer, and then use strtoul to convert the char content to an unsigned integer. However, this doesn't work as intended (in fact, it results in printing "sizeof array = 0"), and so adapt to a simpler fscanf example. Also remove some ambiguous language in the example output.
This commit is contained in:
parent
44ca091c73
commit
b31fda3a8e
@ -148,15 +148,10 @@ int main (int argc, char** argv)
|
|||||||
printf("Enter the array size: "); // ask the user for an array size
|
printf("Enter the array size: "); // ask the user for an array size
|
||||||
int size;
|
int size;
|
||||||
fscanf(stdin, "%d", &size);
|
fscanf(stdin, "%d", &size);
|
||||||
char buf[size];
|
int var_length_array[size]; // declare the VLA
|
||||||
fgets(buf, sizeof buf, stdin);
|
|
||||||
|
|
||||||
// strtoul parses a string to an unsigned integer
|
|
||||||
size_t size2 = strtoul(buf, NULL, 10);
|
|
||||||
int var_length_array[size2]; // declare the VLA
|
|
||||||
printf("sizeof array = %zu\n", sizeof var_length_array);
|
printf("sizeof array = %zu\n", sizeof var_length_array);
|
||||||
|
|
||||||
// A possible outcome of this program may be:
|
// Example:
|
||||||
// > Enter the array size: 10
|
// > Enter the array size: 10
|
||||||
// > sizeof array = 40
|
// > sizeof array = 40
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user