数组的数组,不同大小的 [英] Array of arrays, with different sizes

查看:118
本文介绍了数组的数组,不同大小的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,即在每一个细胞阵列。例如,大数组被称为改编

I'm having an array, that has arrays in every cell. For example, the big array is called arr:

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

现在的问题是,如果我想打印小ARRS,大阵里面。

Now the problem is, if I want to print the small arrs, inside the big array.

下面是我的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 output is supposed to be something like this:

1 8 4 2 0
1 4 2

但我不能让每个数组的大小,因为的sizeof(*(ARR + I)给我4,这是指针的大小(阵列的名称),并且不是所有的数组它自己。
所以,我能做些什么?

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

谢谢!

推荐答案

问题:

The Problem:

C语言只提供发现的类型的大小的一种方式。
这使之间施加的sizeof 来的微妙差异:

The C language only provides a way of finding the size of types. This gives the subtle differences between applying sizeof to:

1)一类的数组,例如:

1) An array of a type such as:

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

2)的指针类型:

2) A pointer to the type:

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

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

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

一些解决方案:

Some solutions:

存储大小

正如jfly提出存储阵列的尺寸。

As jfly proposes store the size of the arrays.


  • 使得寻找大小恒定时间操作。

附加的结束标记

添加像 A结束标志'\\ 0'作为用于C风格的字符串。
您可以使用 INT_MAX INT_MIN 在这种情况下。

Adding a end marker like '\0' as used for c-style strings. You might use INT_MAX or INT_MIN in this case.

printArr 的实施将需要更改为:

The printArr implementation would need to change to:

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

缺点:


  • 查找数组的大小需要迭代全数组。

  • 给出的实际值与最终标记值发生碰撞的危险。

优点:


  • 的不同大小的数组可以作为一个单独的参数传递。

使用迭代器

存储的指针第一和一个过去的最后一个值。

Store the pointer to the first and one past the last value.

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]);
}


  • 可以扩展到其它的数据结构。

  • 这篇关于数组的数组,不同大小的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆