[英]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.目标是创建一个Foo
指针数组,为每个元素赋予有意义的值,然后返回指针数组。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.