简体   繁体   中英

How to create, modify, and return array of pointers in a function in C?

Here's a very basic example of what I'm trying to do (note that this segmentation faults)

#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;
}

the goal is to create an array of pointers of Foo , give each element meaningful values, and then return the pointer array.

Is anyone able to point me in the right direction as to why this doesn't work and how I can accomplish this task?

#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;
}

The output is :

0
1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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