Thread: 2D Array length

1. 2D Array length

So, I'm clearly not understanding something, but I can't seem to be able to determine the length of my array. I have a
int **sat_data array, which is a set length array (i know that length) of other int arrays that vary in length. I need to be able to figure out the length of any given 'inner' array, and I don't understand what I'm doing (probably very) wrong:

Here is an example of an issue I don't get:

Code:
```        printf("One value [297,0]: %d\n", sat_data[297][0]);
printf("One value [297,1]: %d\n", sat_data[297][1]);
printf("One value [297,2]: %d\n", sat_data[297][2]);

int num_elements = sizeof(sat_data );
printf("\nsat_data total: %i \n",num_elements);

num_elements = sizeof(sat_data[297] );
printf("\nsat_data total: %i \n",num_elements);

num_elements = sizeof(sat_data[297])/sizeof( int * );
printf("\nsat_data total: %i \n",num_elements);```
First prints show that I have the date I want in the array (at position 297, it should have 3 values inside and it does), but I cannot get the code to tell me the length (which should be 3):

Output:
One value [297,0]: -55
One value [297,1]: -64
One value [297,2]: 32

sat_data total: 4
sat_data total: 4
sat_data total: 1

Any ideas where i'm messing up? :/

2. If sat_data is just a pointer to a pointer of ints then you can't get the size of a sat_data[x]. size_of will just return the size of a pointer.
But you should know. After all you have allocated the space.
if they are all different sizes then you have to keep trakk of the sizes in a separate array.
Kurt

3. Yea, they are of different lengths. I thought there might be a 'cleaner' way to determine the size of it, but it looks like a separate array it is Thanks!

4. Say your data is this:

10 20 30
2 4 6 8 10 12
1 2 3 4

One possibility is to use a sentinel value at the end. If 0 or -1 are unused in your data, then use one of them. If all values are used, you might use INT_MIN for the sentinel.

10 20 30 -1
2 4 6 8 10 12 -1
1 2 3 4 -1

Another possibility is to store the length of the array as the first element.

3 10 20 30
6 2 4 6 8 10 12
4 1 2 3 4

5. Another solution is to keep an array that holds the length of the corresponding cell.The first cell of this array can hold the length of the first array of sat_data,the second cell the length of second array of sat_data,and so on

Popular pages Recent additions