【发布时间】: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+ 只是为了表达您的担忧并向我们展示代码:)