我試圖使用一個數組來保存一個調查的輸入,每一邊都有相等的正值,但有一個指向數組中心的指針,因此可以使用負指針值訪問數組。指針,數組,printf
例如,數組的值將保持在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+只是爲了說明您的疑慮並向我們展示代碼:) – Skurmedel 2010-01-29 17:43:54
輸出是什麼? – 2010-01-29 17:45:20