首页 > 解决方案 > 如何在 C 中的函数中创建、修改和返回指针数组?

问题描述

这是我正在尝试做的一个非常基本的示例(请注意,此分段错误)

#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    int *bar;
} Foo;

Foo **fooPointers() {
    Foo **test = (Foo**) malloc(sizeof(struct foo) * 3);
    for(int i = 0; i < 3; i++) {
        Foo *curr = *(test + i);
        int *num = &i;
        curr->bar = num;
    }
    return test;
}

int main() {
    fooPointers();
    return 0;
}

目标是创建 的指针数组Foo,为每个元素赋予有意义的值,然后返回指针数组。

有没有人能够指出我为什么这不起作用以及我如何完成这项任务的正确方向?

标签: arrayscpointerssegmentation-faultdouble-pointer

解决方案


#include <stdio.h>
#include <stdlib.h>

typedef struct foo
{
    int *bar;
} Foo;

Foo **fooPointers()
{
    Foo **test = malloc(sizeof(Foo*) * 3);  // should be `sizeof(Foo*)`
    
    static int k[] = {0,1,2};  // new array

    for(int j=0;j<3;j++)
    {
        test[j] = malloc(3*sizeof(Foo));  // No need to cast output of malloc
    }

    for (int i = 0; i < 3; i++)
    {
        Foo *curr = *(test + i);
        //int *num = &i;
        curr->bar = &k[i]; // storing different addresses.
    }
    return test;
}

int main()
{
    Foo **kk;

    kk = fooPointers();

    for(int i=0;i<3;i++)
    {
        printf("%d\n", *(kk[i]->bar));  //printng the values.
    }
    return 0;
}

输出是:

0
1
2

推荐阅读