In C, arrays and strings are closely related. In fact, a string in C is simply an array of characters terminated by a null character ('\0'). When passing arrays and strings to functions, we can use similar concepts of call by value and call by reference.
#include <stdio.h>
// Function to double each element of an array
void doubleArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
doubleArray(numbers, size);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
#include <stdio.h>
// Function to print the length of a string
void printStringLength(char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
printf("Length of the string: %d\n", length);
}
int main() {
char message[] = "Hello, world!";
printStringLength(message);
return 0;
}