diff options
| author | Walt Mankowski <waltman@pobox.com> | 2025-06-22 10:55:21 -0400 |
|---|---|---|
| committer | Walt Mankowski <waltman@pobox.com> | 2025-06-22 10:55:21 -0400 |
| commit | c9918ff51ba59e4778ec4b2c9580610faaf009ba (patch) | |
| tree | 41ff03e7b19505510fb1254c5b99f006d7b36c3d | |
| parent | 32aec247e56e9df31e849d885df2c5cf075663bc (diff) | |
| download | perlweeklychallenge-club-c9918ff51ba59e4778ec4b2c9580610faaf009ba.tar.gz perlweeklychallenge-club-c9918ff51ba59e4778ec4b2c9580610faaf009ba.tar.bz2 perlweeklychallenge-club-c9918ff51ba59e4778ec4b2c9580610faaf009ba.zip | |
moved computation of output length to a function
| -rw-r--r-- | challenge-326/walt-mankowski/c/ch-2.c | 18 |
1 files changed, 12 insertions, 6 deletions
diff --git a/challenge-326/walt-mankowski/c/ch-2.c b/challenge-326/walt-mankowski/c/ch-2.c index 415aff1ec3..7b116cac04 100644 --- a/challenge-326/walt-mankowski/c/ch-2.c +++ b/challenge-326/walt-mankowski/c/ch-2.c @@ -1,6 +1,14 @@ #include <stdio.h> #include <stdlib.h> +size_t compute_output_len(int argc, char *argv[]) { + size_t output_len = 0; + for (int i = 1; i < argc; i += 2) + output_len += atoi(argv[i]); + + return output_len; +} + int main (int argc, char *argv[]) { if (argc % 2 != 1) { fputs("There should be an even number of parameters\n", stderr); @@ -8,10 +16,8 @@ int main (int argc, char *argv[]) { } /* compute how big the output array should be */ - size_t output_size = 0; - for (int i = 1; i < argc; i += 2) - output_size += atoi(argv[i]); - unsigned int *output = malloc(output_size * sizeof(unsigned int)); + size_t output_len = compute_output_len(argc, argv); + unsigned int *output = malloc(output_len * sizeof(unsigned int)); /* add things to the output array */ int k = 0; @@ -24,7 +30,7 @@ int main (int argc, char *argv[]) { /* print out the array */ printf("("); - for (int i = 0; i < output_size-1; i++) + for (int i = 0; i < output_len-1; i++) printf("%u, ", output[i]); - printf("%u)\n", output[output_size-1]); + printf("%u)\n", output[output_len-1]); } |
