【问题标题】:How to access an double pointer type argument as 2D array? [duplicate]如何将双指针类型参数作为二维数组访问? [复制]
【发布时间】:2016-03-23 21:54:27
【问题描述】:

类似这样的:

struct s
{
    int a;
    int b;
}

void f(struct s **a)
{
    a[0][0].a = 0; // Access violation here
}

int main()
{
    struct s a[5][3];
    f(a);
    return(0);
}

那么如何使用二维数组表示法访问内部函数 f 的内容?

【问题讨论】:

  • 你为什么不用a以外的东西?
  • 指针不是数组,数组也不是指针!
  • @SouravGhosh 我必须在手机上输入代码(并格式化它们),所以我试图让它变得简单。很抱歉给您带来不便。

标签: c arrays


【解决方案1】:

a[5][3] 这样的数组连续存储struct 实例,而struct s **a 将连续存储指针,这样每个指针都指向struct s 的一个实例。所以struct s a[5][3]自动转换为指针)和struct s **a是不兼容的指针,如果你编译时有警告你会知道的。

一个简单的解决方案是

void f(struct s a[][3])
{
    a[0][0].a = 0; // Access violation here
}

更好的解决方案是

#include <stdlib.h>

struct some_structure
{
    int value1;
    int value2;
};

void
set_value(struct some_structure **array, size_t row, size_t column)
{
    array[row][column].value1 = 0;
    array[row][column].value2 = 0;
}

int
main(void)
{
    struct some_structure **array;
    array = malloc(5 * sizeof(*array));
    if (array == NULL)
        return -1; // Allocation Failure
    for (size_t i = 0 ; i < 5 ; ++i)
    {
        array[i] = malloc(sizeof(*(array[i])));
        if (array[i] == NULL)
            return -1; // Allocation Failure
    }
    set_value(array, 0, 0);
    for (size_t i = 0 ; i < 5 ; ++i)
        free(array[i]);
    free(array);
    return 0;
}

正如我在上面所说的那样,将存储指针这是因为您需要为此分配内存,您可以像上面的示例一样使用malloc()

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 2011-11-27
    • 1970-01-01
    • 2019-03-17
    • 2016-05-28
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多