Array of arrays of different sizes

I have an array that has arrays in each cell. For example, a large array is called arr:

int a[3] = {3, 2, 1};
int b[2] = {2, 1};
int *arr[2] = {a, b}

Now the problem is that if I want to print small arrs inside a large array.

Here is my code:

#include <stdio.h>

void printArr(int arr [], int n)
{
    for (int i = 0 ; i < n ; i++)
    {
        printf("%d ", *(arr + i));
    }
    printf("\n");
}

int main()
{
    int a[5] = {1, 8, 4, 2, 0};
    int b[3] = {1, 4, 2};
    int *arr [2] = {a, b};

    int n = 0;

    for (int i = 0 ; i < 2 ; i++)
    {
        printArr(*(arr + i), n);
    }
}

The result should be something like this:

1 8 4 2 0 1 4 2

But I can’t get the size of each array, since it sizeof(*(arr + i)gives me 4, this is the size of the pointer (array name), not the whole array. So what can I do?

Thank!

+4
source share
2 answers

Problem:

C provides only a way to determine the size of types. This gives subtle differences between application sizeofto:

1) An array of the type such as:

int a[3];
sizeof(a); // => 3 * sizeof(int)

2) Pointer to type:

int *ptr;
sizeof(ptr); // => sizeof(int *)

or

int a[3] = {3, 2, 1};
int b[2] = {2, 1};
int *arr[2] = {a, b};

sizeof(arr[1]); // => sizeof(int *)

:

jfly .

  • .

, '\0', c-style. INT_MAX INT_MIN.

printArr :

void printArr(int *arr)
{
    int *it = arr;
    while(arr != INT_MIN);
    {
        printf("%d ", *it);
    }
    printf("\n");
}

:

  • .
  • , .

:

  • .

.

void printArr(int *begin, int *end)
{
    for (int *it = begin; it != end; it++)
    {
        printf("%d ", *it);
    }
    printf("\n");
}

int *end_arr[2] = {a + 3, b + 2};

for (int i = 0 ; i < 2 ; i++)
{
    printArr(arr[i], end_arr[i]);
}
  • .
+7

arr - , , , :

    int size_arr[2] = {sizeof(a) / sizeof(int), sizeof(b) / sizeof(int)};

    for (int i = 0 ; i < 2 ; i++)
    {
        printArr(arr[i], size_arr[i]);
    } 
+1

Source: https://habr.com/ru/post/1534132/


All Articles