我正在尝试使用一个数组来保存调查的输入,该调查的每一侧都具有相同的正值,但有一个指针指向数组的中心,因此可以使用负指针值来访问该数组。
例如,数组将保存从 0 到 30 的值,指针将指向 15,系统将提示用户输入 -15 到 15 之间的值,其中用户值所在的数组将递增。
如果我的逻辑还不完全正确,我没关系,但我现在遇到的问题是增加值(我不确定我是否正确地做到了这一点)ptr[userInput]++
,并输出这些值printf
。我看到别人的帖子关于将数组传递给printf
实际上是传递一个指向数组的指针,那个人说用以下任一方法取消引用它两次**ptr
or (*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.
}
}
就您在问题中提出的直接问题而言,您的代码完全没问题。 IE。您正在正确使用“双面”数组(不,当您printf
数组中的值)。
我看到的一个问题是您忘记初始化(分配初始值)您的record
数组,这意味着无论您如何使用它,输出无论如何都是垃圾。
另外,正如 Dave Hinton 在评论中指出的那样,如果您想使用-ENDPOINT
to +ENDPOINT
范围从ptr
起源,你需要初始化你的ptr
with &record[ENDPOINT]
,不与&record[ENDPOINT + 1]
。否则,如果用户输入ENDPOINT
value 作为索引,最终会在右端出现越界访问。 (并且值record[0]
左端将始终保持未使用状态。)
附:我会做一些“风格”的改变,但在这种情况下它们不是重点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)