我有一个函数,该函数接收到char数组的指针。该功能会递增指针,从而使其穿过n长度穿过数组。最后,函数返回一个表示某些状态的int。问题是我还有其他功能,他们还收到了指向相同的char阵列的指针,他们需要开始准确地穿越其他功能。因此,我需要以某种方式保存指针的地址。我无法返回指针,因为功能返回int。我想知道我是否仍然可以以某种方式实现此操作,或者我需要使用结构来保存多种数据类型(INT和指针地址)。
这是这样一个功能的示例:
int func(char *p) {
while(*p != 's')
p++;
return (*p == 's') ? 1 : -1
}
您可以编辑指针:
// The ** means a pointer to a pointer, you can now edit the pointer.
int func(char **p) {
// Mauybe check for the end of the string here as well.
while(*(*p) != 's') {
// We dereference our pointer and edit it here.
(*p)++;
}
return (*(*p) == 's') ? 1 : -1
}
在此功能的末尾,您的p
将指向循环停止的位置。您会这样称呼:
char *p = someString;
int myInt = func(&p);
如果固定了函数签名,则在不使用全局的情况下,这是不可能的,或者在第二个功能中使用相同的循环来"重新找到"此位置。
<</p>我恐怕您必须使用双重指针。通过将论点更改为char **,在这种情况下,该函数看起来会更丑陋,或者添加一个新的" out"类型char **的" out"参数,这是指针的地址,其中新值的新值指针将存储 - 有点模拟另一个返回值。
这是第一个选项:
int func(char **p) {
while (**p != 's')
++*p;
return **p == 's' ? 1 : -1;
}
您可以返回包含状态和指针的结构,也可以制作全局指针
指针指针如何:
int func(char **p) {
while(**p != 's')
(*p)++;
return (**p == 's') ? 1 : -1;
}
您将使用:
来调用它func(&pointer);