Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM_ROWS 3
- int main() {
- /**
- * In this demo, we'll be creating an irregular 2D array with 3 rows.
- */
- int **array = NULL;
- int numCols;
- int len[3]; // array to store row length for printing only, you can disregard this
- // 1. First Dimension
- array = (int**) malloc(sizeof(int *) * NUM_ROWS);
- // 2. Second Dimension
- for (int row = 0; row < NUM_ROWS; row++) {
- do {
- // Prompt for number of rows
- printf("Number of columns for row %i: ", row + 1);
- scanf("%i", &numCols);
- len[row] = numCols; // store current number; disregard this
- } while (numCols < 1);
- // Allocate number of row
- array[row] = (int*) malloc(sizeof(int) * numCols);
- // Pre-fill array
- for (int col = 0; col < numCols; col++) {
- array[row][col] = numCols;
- }
- }
- // Printing
- printf("\n");
- for (int row = 0; row < NUM_ROWS; row++) {
- printf("ROW %i: ", row + 1);
- for (int col = 0; col < len[row]; col++) {
- printf("[%2i] ", array[row][col]);
- }
- printf("\n");
- }
- // Freeing
- for (int row = 0; row < NUM_ROWS; row++) {
- free(array[row]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement