【问题标题】:Pointer Initialization to Iterate through Array指针初始化以迭代数组
【发布时间】:2015-02-07 01:08:21
【问题描述】:

我有一个函数,其中有 2 个 void 指针(规范的一部分),但我知道它们是 char *。我想遍历 char 数组,所以我尝试创建一些指针来遍历它们。当我执行以下操作时,我的程序不起作用:

int foo(void const * first, void const * second)
{
    char const * firstIt = (const char*) first;
    char const * secondIt = (const char*) second;
    ...
}

但是,如果我这样做:

int foo(void const * first, void const * second)
{
    char const * firstIt = *(const char**) first;
    char const * secondIt = *(const char**) second;
    ...
}

两者有什么区别,为什么第二个有效?我不知道我是否包含了足够的细节,所以如果需要更多信息,我很乐意提供。

【问题讨论】:

  • 没有足够的信息,我试过第一个对我有用

标签: c pointers void-pointers


【解决方案1】:

如果第二个有效,这是因为您为函数指示的 void 指针实际上可以是任何东西,我猜您正在将指针的指针传递给函数。例如,以下代码有效:

#include <stdio.h>
#include <stdlib.h>

int foo(void const * first, void const * second);
int goo(void const * first, void const * second);

int main () {
    char * a, * b;

    a = malloc (sizeof (char));
    b = malloc (sizeof (char));

    *a = 'z';
    *b = 'x';

    goo (&a, &b); /* critical line */

    free (a);
    free (b);

    return 0;
}

int foo(void const * first, void const * second) {
    char const * firstIt  = (const char*) first;
    char const * secondIt = (const char*) second;    
    printf ("%c %c", *firstIt, *secondIt);
    return 1;
}

int goo(void const * first, void const * second) {
    char const * firstIt = *(const char**) first;
    char const * secondIt = *(const char**) second;
    printf ("%c %c", *firstIt, *secondIt);
    return 2;
}

但是,要使上述程序与函数 foo 一起工作,您需要将关键行替换为以下形式的调用:

foo (a, b);

区别有意义吗?解决了你的问题吗?

【讨论】:

    【解决方案2】:

    第一种方法假设调用者传递了一个 char *(以某种方式限定的 const)。

    第二个假设调用者传递了一个 char **(以某种方式限定的 const)。

    如果第二个有效,这意味着您的调用者正在传递一个 char **。

    第一个不起作用的原因是未定义的行为。拥有一种类型的指针,转换为另一种类型,并将其取消引用为原始类型以外的任何类型都会产生未定义的行为。通过 void 指针进行的往返不会改变这一点。

    这就是为什么编译器会抱怨一种指针类型到另一种类型的隐式转换(除了 void 指针和来自 void 指针)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多