arrays - 如何在 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
,为每个元素赋予有意义的值,然后返回指针数组。
有没有人能够指出我为什么这不起作用以及我如何完成这项任务的正确方向?
解决方案
#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
推荐阅读
- c++ - 使用 Bazel 使用不同的编译器/链接器选项构建 C/C++ 依赖项
- javascript - 从 html 视频元素到小的屏幕截图
- python - 在数据框列中搜索字符串模式,返回每个出现并加入另一个数据框
- swift - 在 Swift 中浮动的 Uint8 数组
- java - FireBaseListAdapter的Android工作室错误
- sql-server - 使用 Azure AD 时审核 SQL 表
- php - SQLSTATE [HY000]:一般错误:1364 字段“名字”没有默认值(SQL:插入“用户”(“电子邮件”)值(test@test.com))
- python - 如何避免模型在 keras Tensorflow 中变成层
- ios - CoreData派生属性查看一对多关系是否包含属性
- pandas - 在 Pandas 中操作列时出现内存错误