我有一个数组,想将它传递给一个函数,该函数需要指针数组作为参数,当我将它与引用一起传递时,它只给我该数组的第一个元素。我究竟做错了什么?这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct abc{
int a;
};
void a(struct abc* j[]){
printf("%d\n",j[1]->a);
}
int main()
{
struct abc* k = malloc(2 * sizeof(struct abc));
k[0].a = 2;
k[1].a = 3;
a(&k);
return 0;
}
提前致谢
最佳答案
编辑:您目前没有创建指针数组。您当前正在创建一个结构数组。要创建指针数组,请执行以下操作:
#include <stdio.h>
#include <stdlib.h>
struct abc{
int a;
};
void a(struct abc* j[]){
printf("%d\n",j[1]->a);
}
int main()
{
struct abc **k = malloc(2 * sizeof(struct abc *));
k[0] = malloc(sizeof(struct abc));
k[1] = malloc(sizeof(struct abc));
k[0]->a = 2;
k[1]->a = 3;
a(k);
return 0;
}
旧:如果你只想用一个结构数组来做:
#include <stdio.h>
#include <stdlib.h>
struct abc{
int a;
};
void a(struct abc* j){
printf("%d\n",j[1].a);
}
int main()
{
struct abc* k = malloc(2 * sizeof(struct abc));
k[0].a = 2;
k[1].a = 3;
a(k);
return 0;
}
关于c - 无法读取指针数组的元素,第 0 个元素除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437525/