c - 无法读取指针数组的元素,第 0 个元素除外

标签 c arrays

我有一个数组,想将它传递给一个函数,该函数需要指针数组作为参数,当我将它与引用一起传递时,它只给我该数组的第一个元素。我究竟做错了什么?这是我的代码:

#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/

相关文章:

比较某些部分可变但无关紧要的图像

c - 使用C中的链接列表将数字添加为字符串

java - 检查 String[] 中的 String 是否在 ArrayList<string> 中

c - 无类型 union (没有类型标签)有什么用处吗?

c++ - 如何使用 C 宏 (#define) 来改变调用而不是原型(prototype)

arrays - 按 Int 数组对字符串数组进行排序

java - 从 JSONArray 获取字符串到 String[] 或 List<String> 以输入到 ArrayList

java.lang.UnsupportedOperationException 但没有 Arrays.asList()

C 编程团队随机化

python - Cython Memoryview 段错误