[英]Why does my C program output the memory address instead of the value?
為什么我的 C 程序 output 是 memory 地址而不是值?
我基本上只是將用戶輸入作為一個整數數組,然后嘗試遍歷數組以打印出每個元素,但是一旦程序運行,它就會輸出我猜元素的“內存地址”而不是它的實際價值。
請看下面的代碼:
#include <stdio.h>
int main(void) {
int array[5]; //the array with x items
int target = array[1]; //target is any second value of the array
for (int y = 0; y < 5; y++){ //taking 5 user inputs
if (y == 0){
printf("Enter your %dst item: ", y+1);
scanf("%d", &array[5]);
} else if (y == 1){
printf("Enter your %dnd item: ", y+1);
scanf("%d", &array[5]);
} else if (y == 2){
printf("Enter your %drd item: ", y+1);
scanf("%d", &array[5]);
} else{
printf("Enter your %dth item: ", y+1);
scanf("%d", &array[5]);
}
}
for (int x=0 ; x < 5; x++){ //printing out array
printf("Array[%d] = %d\n", x, array[x]);
}
}
謝謝!
您沒有為數組分配任何值。
int target = array[1];
沒有意義,因為數組沒有初始化。 C 程序從上到下執行,賦值不會在變量之間創建一些神奇的關系:如果array[1]
最終被初始化, target
不會在以后神奇地更新。 如果你想要這樣的東西,你可以使用指針。
&array[5]
沒有意義,因為 C 中的 arrays 是 0 索引的,您可以通過寫入第 6 項來越界訪問數組。 這會導致未定義的行為,未定義行為的一種可能結果是 memory 損壞。
printf("Array[%d] = %d\n", x, array[x]);
沒有意義,因為數組還沒有被初始化。 打印的值將具有不確定的值,它可以是任何值。
你可以像這樣修復你的程序:
#include <stdio.h>
int main (void)
{
int array[5];
int* target = &array[1];
for (int i = 0; i < 5; i++)
{
const char* nstr[] = {"st", "nd", "rd", "th"};
int index;
if(i > 3)
index = 3;
else
index = i;
printf("Enter your %d%s item: ", i+1, nstr[index]);
scanf("%d",&array[i]);
}
for (int i=0; i < 5; i++)
{
printf("Array[%d] = %d\n", i, array[i]);
}
printf("Target: %d\n", *target);
}
Output & 輸入示例:
Enter your 1st item: 1
Enter your 2nd item: 2
Enter your 3rd item: 3
Enter your 4th item: 4
Enter your 5th item: 5
Array[0] = 1
Array[1] = 2
Array[2] = 3
Array[3] = 4
Array[4] = 5
Target: 2
首先,你還沒有像你一樣讀過這個數組。 這個更好:
for (int y = 0; y < 5; y++){ //taking 5 user inputs
printf("Enter your %dst item: ", y+1);
scanf("%d", &array[y]);
}
請注意,我讀的是 &array[y],但不是 &array[5]。 您必須將 scanf 作為 arg 數據的目的地地址。 是一樣的
for (int y = 0; y < 5; y++){ //taking 5 user inputs
printf("Enter your %dst item: ", y+1);
scanf("%d", array+y);
}
所以,你正確的編將是這樣的:
int main(void) {
int array[5]; //the array with x items
//int target = array[1]; //target is any second value of the array I dont know what you want here
for (int y = 0; y < 5; y++){ //taking 5 user inputs
printf("Enter your %dst item: ", y+1);
scanf("%d", array+y);
}
for (int x=0 ; x < 5; x++){ //printing out array
printf("Array[%d] = %d\n", x, array[x]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.