c - 在 C 中,如何访问指针数组(作为参数传递)

标签 c arrays list pointers

我是一名初学者(C 语言),正在尝试编写一个简单的自动机。我有一个包含 50 个指向 lTransitions 类型结构的指针的数组 automaton[]。我想调用 addTransition(&automaton, s1, &t) 向列表添加一个转换(t 指向刚刚用 malloc() 创建的结构) > ...)。如果 automaton[state1]NULL 那么我需要用 t 指向的地址替换它。否则,我需要跟随链直到 automaton[state1]->nextNULL

问题是测试总是返回 false,因为 *(automaton+e1) 是指针的地址,而不是它应该指向的结构(如果没有则返回 NULL)。

如有任何帮助,我们将不胜感激。

以下是我的代码的关键行:

struct lTransitions { char   c;
                      int    stateNext;
                      struct lTransition *next };

struct lTransitions *automaton[50]=NULL;

void addTransition( struct lTransition **automaton, int state1, struct lTransition *t){
...
if (*(automaton+e1)==NULL) { *(automaton+e1) = t; }
    else { ... }

最佳答案

因为你传递的是整个数组的地址而不是数组,你不能访问它的元素,你需要在访问元素之前取消引用它:

if (*((*automaton)+e1)==NULL) ...

或者更好的写法:

if ((*automaton)[e1] == NULL) {
    (*automaton)[e1] = t;
}

automaton 是指向数组的指针,(*automaton) 是数组。

不过,此代码的正确性取决于您调用该函数的方式,并且您已经从您的示例中删除了它。下次写一个完整的例子。

关于c - 在 C 中,如何访问指针数组(作为参数传递),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122959/

相关文章:

java - Java中将字符串转换为二维字符串数组

python - 设置转换的列表的时间复杂度是多少?

c - 每次编译参数返回不同的值

c - 使用进程通过管道运行命令

javascript - JS : Regex and global match() not creating an array

python - 在给定条件的情况下在 numpy 数组中填充值

c# - 使用 LINQ 从索引不等于 int 的列表中获取项目

python - 自定义排序列表,了解一些项目的顺序

c - 使用 .so(共享对象)中的内存映射文件

c - 如何从 ASN1 创建 .DER