繁体   English   中英

使用单指针或双指针将指针返回到结构体数组

[英]Returning pointer to an array of struct with single or double pointer

我的代码的目标如下:

  1. 通过单指针或双指针返回指向innerStruct数组的指针(我相信我应该使用双指针)

  2. 将该指针传递给修改值的函数

似乎在在线编译器中出现段错误。

#include <stdio.h>

typedef struct
{
    int innerVal;

} innerStruct;

typedef struct
{
    int           a;
    innerStruct * inner[3];

} myStruct;

static myStruct * m1;

innerStruct ** getInnerPtrToArray()
{
    return &(m1->inner);
}

void processInnerStruct(innerStruct * array_ptr[])
{
    for(int i=0; i<3; i++)
    {
        array_ptr[i]->innerVal = i;
    }
}

int main() 
{
    innerStruct ** array_ptr = getInnerPtrToArray();
    processInnerStruct(array_ptr);

    return 0;
}

在线编译器: https : //onlinegdb.com/r1z0DPICb

由于inner是指针数组,因此您需要分配内存以供它们指向。 您还需要分配内存以供m1指向。

int main() 
{
    m1 = malloc(sizeof(myStruct));
    for (int i = 0; i < 3; i++) {
        m1->inner[i] = malloc(sizeof(innerStruct));
    }
    innerStruct ** array_ptr = getInnerPtrToArray();
    processInnerStruct(array_ptr);

    return 0;
}

这是您正在做的事情的第二种切入点。 除了分配外,还可以将myStruct更改为仅包含一个innerStruct数组,而不是一个指向innerStruct的指针数组 则不需要分配,例如

#define NINNER 3    /* if you need a constant, define one */
...
typedef struct {
    int           a;
    innerStruct inner[NINNER];   /* you are not allocating */
} myStruct;

注意:避免使用全局变量,不需要它们。 main()声明变量,并根据需要作为参数传递。

总而言之,根据需要调整类型,并在下面的注释中添加更多注释作为注释,您可以执行以下操作:

#include <stdio.h>

#define NINNER 3    /* if you need a constant, define one */

typedef struct {
    int innerVal;
} innerStruct;

typedef struct {
    int a;
    innerStruct inner[NINNER];   /* you are not allocating */
} myStruct;

/* takes pointer to m1, returns address of array of 3 innerStruct */
innerStruct *getInnerPtrToArray (myStruct *innerptr)
{
    return innerptr->inner;
}

/* takes pointer to array of innerStruct, fills */
void processInnerStruct (innerStruct *array_ptr)
{
    for (int i = 0; i < NINNER; i++)
        array_ptr[i].innerVal = i;
}

int main (void) {

    myStruct m1 = { .a = 10 };  /* don't use globals */
    /* pass the address of m1 */
    innerStruct *array_ptr = getInnerPtrToArray (&m1);
    processInnerStruct (array_ptr);

    printf ("m1.a: %d\n", m1.a);        /* output values */
    for (int i = 0; i < NINNER; i++)
        printf ("  .inner[%d]: %d\n", i, m1.inner[i].innerVal);

    return 0;
}

使用/输出示例

$ ./bin/inner
m1.a: 10
  .inner[0]: 0
  .inner[1]: 1
  .inner[2]: 2

由您决定是否要为innerStruct中的3 innerStruct myStruct ,但从我对您要执行的操作的阅读中(不包括stdlib.h ,看来您的意图是处理数组而不分配。 如果您还有其他问题,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM