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