【问题标题】:Pointers, Arrays, printf指针、数组、printf
【发布时间】:2010-01-29 17:41:14
【问题描述】:

我正在尝试使用一个数组来保存调查的输入,该调查将在每一侧具有相等的正值,但有一个指向数组中心的指针,因此可以使用负指针值来访问数组。

例如,数组将保存从 0 到 30 的值,指针将指向 15,并且将提示用户输入 -15 到 15 之间的值,其中用户值的数组将递增。

如果我的逻辑还不完全正确,我没问题,但我现在遇到的问题是增加值(我不确定我是否按 ptr[userInput]++ 正确执行,并输出这些值与printf。我看到其他人关于将数组传递给printf 的帖子实际上是在传递一个指向数组的指针,并且那个人说用**ptr(*ptr)[0] 取消引用它两次,但是我的编译器(Mac XCode)似乎不喜欢它。

有什么想法吗?这是我的代码。我评论了我的问题所在:

#define ENDPOINT 15
#define TERMINATE 999
#define TEST_FILE "TestFile6.txt"

void RecordOpinions(void)
{
    int record[2 * ENDPOINT + 1];
    int *ptr = &record[ENDPOINT + 1];
    int userInput;
    int loopCount = -ENDPOINT;

    printf("ptr:%d\n", *ptr);  // this was a test for me trying to figure out how to 
                               // print the value of the ptr.

    printf("Please enter your opinion of the new TV show, Modern Family from ");
    printf("-%d(worst) to 0 to +%d(best).  Entering %d ", ENDPOINT, ENDPOINT, TERMINATE);
    printf("will terminate and tabulate your results: \n");

    scanf("%d", &userInput);
    while (userInput != TERMINATE) {
        if (userInput > ENDPOINT || userInput < -ENDPOINT) {
            printf("Invalid entry.  Enter rating again: ");
        }
        else {
            printf("You entered: %d\n", userInput);

            ptr[userInput]++;      // not sure if this is the right way to increment 
                                   // the array at the user's input value.
        }
        scanf("%d", &userInput);
    }
    printf("Rating entry terminated.\n");
    printf("Ratings:.\n");
    for (; loopCount <= ENDPOINT; ) {
        printf("%d\n", ptr[loopCount++]);   // this part is where I also need help
                                                // in trying to print out the value of
                                                // the ptr, not the address.
    }
}

【问题讨论】:

  • 1+ 只是为了表达您的担忧并向我们展示代码:)

标签: c pointers printf


【解决方案1】:

就您在问题中提出的直接问题而言,您的代码非常好。 IE。您正在正确使用“双面”数组(不,当您 printf 数组中的值时,您不需要任何额外的取消引用)。

我看到的一个问题是您忘记初始化(分配初始值)您的record 数组,这意味着无论您如何使用它,输出都将是垃圾。

此外,正如 Dave Hinton 在 cmets 中指出的那样,如果您想使用来自 ptr 原点的 -ENDPOINT+ENDPOINT 范围,您需要使用 &amp;record[ENDPOINT] 初始化您的 ptr,而不是使用 @ 987654328@。否则,如果用户输入ENDPOINT 值作为索引,您将在右端获得越界访问。 (并且record[0] 的值在左端将始终保持未使用状态。)

附:我会做很多“风格”的改变,但在这种情况下它们是无关紧要的。

【讨论】:

  • 我认为他们也可能意味着初始化 int *ptr = &amp;record[ENDPOINT]; 而不是 int *ptr = &amp;record[ENDPOINT + 1];
  • 感谢初始化的帮助。现在这是有道理的。我现在遇到的问题是让自己相信戴夫所说的话。我试图把它画出来,我的 arrary 记录有 31 个值,从 0 到 30。但是,如果我希望 ptr 的原点有 +15 和 -15,它是否必须指向记录数组上的数字 15,实际上是数组的第 16 个索引?我的意思是我看到它实际上不适用于等于 ENDPOINT + 1 并且 Dave 是正确的,但我不明白为什么它不正确等于 ENDPOINT + 1。再次感谢!
【解决方案2】:

为什么不从用户输入的数字中减去 15? IE。

ptr[userInput - ENDPOINT]++;

ptr 指向数组的开头?这更容易理解,也更传统。

【讨论】:

  • 恰恰相反。如果问题的性质要求将负索引和正索引映射到数据,则 OP 使用的方法明显更加优雅和可读。事实上,它是惯用的。
猜你喜欢
  • 2012-10-29
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多