#include <stdio.h>
#include <stdlib.h>
int* column_products(int** matrix, int* row_lengths, int rows, int* out_cols) {
// Find the maximum number of columns
int max_cols = 0;
for (int i = 0; i < rows; i++) {
if (row_lengths[i] > max_cols) {
max_cols = row_lengths[i];
}
}
int* products = malloc(max_cols * sizeof(int));
if (!products) return NULL;
// Compute column products
for (int col = 0; col < max_cols; col++) {
int product = 1;
for (int row = 0; row < rows; row++) {
if (col < row_lengths[row]) {
product *= matrix[row][col];
}
}
products[col] = product;
}
*out_cols = max_cols;
return products;
}
int main(void) {
// Equivalent to: int[][] matrix = { {1,2,3}, {4,5}, {6,7,8,9} };
int row0[] = {1, 2, 3};
int row1[] = {4, 5};
int row2[] = {6, 7, 8, 9};
int* matrix[] = { row0, row1, row2 };
int row_lengths[] = { 3, 2, 4 };
int rows = 3;
int cols = 0;
int* result = column_products(matrix, row_lengths, rows, &cols);
if (!result) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Column products: ");
for (int i = 0; i < cols; i++) {
printf("%d ", result[i]);
}
free(result);
return 0;
}
/*
run:
Column products: 24 70 24 9
*/