2

I am trying to code a array with dynamic rows and columns (multi-dimensional).

This is what I've tried:

#include <stdio.h> #include <stdlib.h> #define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0])) int main() { int size, q = 0; // get arr size from stdin scanf("%d", &size); int *arr[size]; for (int i=0; i<size; i++) { int len, element = 0; // get length of column from stdin scanf("%d", &len); arr[i] = malloc(len * sizeof(int)); for(int j=0; j<len; j++) { // get each column's element from stdin and append to arr scanf("%d", &element); arr[i][j] = element; } } for (int i=0; i< LEN(arr); i++) printf("%d\n", LEN(arr[i])); } 

stdin:

2 3 4 5 6 4 1 2 3 4 

The first line of input is the size/amount of arrays to be stored in arr (2), the following lines begin with the size of the columns (3, 4) followed by the elements to store (4 5 6, 1 2 3 4) in each column.

stdout:

2 2 

When I run this program with the output is 2 meaning each column's length is 2, this is unintended. I am seeking for a solution to output the correct column lengths. What am I doing wrong?

The intended stdout is:

3 4 

1 Answer 1

1

arr is an array, so sizeof(arr) gives you the size in bytes of the array as expected.

arr[i] is not an array however. It is a pointer, specifically a int *. So sizeof(arr[i]) gives you the size in bytes of an int *.

When you allocate memory dynamically, you need to keep track of how much space was allocated. You can do this by maintaining a separate array with size size of each subarray.

int *arr[size], arr_len[size]; ... for (int i=0; i<size; i++) { ... arr[i] = malloc(len * sizeof(int)); arr_len[i] = len; ... } for (int i=0; i< LEN(arr); i++) printf("%d\n", arr_len[i])); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.