Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ int string_length_2_(const char(*parameter)[5]) {
return counter;
}


int string_length_3_(char parameter[][5]) {

char* character = parameter;
Expand All @@ -97,3 +98,68 @@ int string_length_3_(char parameter[][5]) {

return counter;
}


#include <stdio.h>
#include <stdlib.h>

#define COLS 5

int* count_lengths(char(*arr)[COLS], int rows) {
int* result = malloc(rows * sizeof(int));
if (!result) {
perror("malloc failed");
exit(1);
}

for (int i = 0; i < rows; i++) {
int len = 0;

// "When an array name is passed to a function, the function can at its convenience believe that
// it has been handed either an array or a pointer, and manipulate it accordingly.
// It can even use both notations if it seems appropriate and clear."[1]:114
for (int j = 0; j < COLS && arr[i][j] != '\0'; j++) {
len++;
}
result[i] = len;
}
return result;
}

int main(void) {

char argument[][5] = {
{'f', 'o', 'a', 'm', '\0'},
{'l', 'i', 'm', 'b', '\0'},
{'l', 'i', 'm', 'p', '\0'},
{'c', 'r', 'i', 'p', '\0'},
"set",
"Acer"
};

// C reserves space for 5 characters regardless of actual number of characters in each row.
// because "the purpose of supplying the size of an array in a declaration is to set aside storage."
// [1][2][3]
int rows = sizeof(argument) / sizeof(argument[0]);

int* lengths = count_lengths(argument, rows);

printf("[");
for (int i = 0; i < rows; i++) {
printf("%d", lengths[i]);
if (i < rows - 1) printf(", ");
}
printf("]\n");

free(lengths);
return 0;
}



// References:
//
// 1. K&RII
// 2. https://chatgpt.com/c/69076ad5-da9c-8323-a59c-5f74c747945f
// 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
//