@@ -80,6 +80,7 @@ int string_length_2_(const char(*parameter)[5]) {
8080 return counter ;
8181}
8282
83+
8384int string_length_3_ (char parameter [][5 ]) {
8485
8586 char * character = parameter ;
@@ -97,3 +98,68 @@ int string_length_3_(char parameter[][5]) {
9798
9899 return counter ;
99100}
101+
102+
103+ #include <stdio.h>
104+ #include <stdlib.h>
105+
106+ #define COLS 5
107+
108+ int * count_lengths (char (* arr )[COLS ], int rows ) {
109+ int * result = malloc (rows * sizeof (int ));
110+ if (!result ) {
111+ perror ("malloc failed" );
112+ exit (1 );
113+ }
114+
115+ for (int i = 0 ; i < rows ; i ++ ) {
116+ int len = 0 ;
117+
118+ // "When an array name is passed to a function, the function can at its convenience believe that
119+ // it has been handed either an array or a pointer, and manipulate it accordingly.
120+ // It can even use both notations if it seems appropriate and clear."[1]:114
121+ for (int j = 0 ; j < COLS && arr [i ][j ] != '\0' ; j ++ ) {
122+ len ++ ;
123+ }
124+ result [i ] = len ;
125+ }
126+ return result ;
127+ }
128+
129+ int main (void ) {
130+
131+ char argument [][5 ] = {
132+ {'f' , 'o' , 'a' , 'm' , '\0' },
133+ {'l' , 'i' , 'm' , 'b' , '\0' },
134+ {'l' , 'i' , 'm' , 'p' , '\0' },
135+ {'c' , 'r' , 'i' , 'p' , '\0' },
136+ "set" ,
137+ "Acer"
138+ };
139+
140+ // C reserves space for 5 characters regardless of actual number of characters in each row.
141+ // because "the purpose of supplying the size of an array in a declaration is to set aside storage."
142+ // [1][2][3]
143+ int rows = sizeof (argument ) / sizeof (argument [0 ]);
144+
145+ int * lengths = count_lengths (argument , rows );
146+
147+ printf ("[" );
148+ for (int i = 0 ; i < rows ; i ++ ) {
149+ printf ("%d" , lengths [i ]);
150+ if (i < rows - 1 ) printf (", " );
151+ }
152+ printf ("]\n" );
153+
154+ free (lengths );
155+ return 0 ;
156+ }
157+
158+
159+
160+ // References:
161+ //
162+ // 1. K&RII
163+ // 2. https://chatgpt.com/c/69076ad5-da9c-8323-a59c-5f74c747945f
164+ // 3. https://github.com/ResilientSpring/The-C-Programming-Language/blob/main/Chapter%201%20-%20A%20Tutorial%20Introduction/1.9%20Character%20Arrays%202/badge%202.c
165+ //
0 commit comments