[英]C - Print Array
我正在嘗試實時打印添加到數組中的元素。
一切似乎都正常,但
例如
我加數字1 2 3
但是結果是: 9966656 2686588 1 2 3
我不知道為什么它也可以打印9966656 2686588 ,而不僅僅是1 2 3
int numbers[100] , c , x;
char answer;
puts("Please insert a value");
GO:
scanf("%d", &numbers[c]);
getchar();
puts("Do you want to add another value? y/n");
scanf("%c",&answer);
if (answer == 'y') {
c = c + 1;
puts("Please insert another value");
goto GO;
} else {
x = c;
for (c = 0; c < x + 1; c++) {
printf("%d ",numbers[c]);
}
}
* =====================
如果您聽不懂,請告訴我*
您需要解決幾個問題。 如果您已在啟用警告的情況下進行編譯,則所有這些代碼都將為您拼寫出來(例如,將-Wall -Wextra
添加到編譯字符串中。)例如:
$ gcc -Wall -Wextra -o bin/go go.c
go.c: In function ‘main’:
go.c:17:5: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[30]’ [-Wformat=]
scanf("%c",&answer);
^
go.c:18:15: warning: comparison between pointer and integer [enabled by default]
if(answer == 'y')
如果在代碼沒有警告的情況下編譯代碼之前就解決了所有警告,那么您將遇到主要問題:
for(c = 0; c < x + 1; c++)
x + 1
使循環讀取超出數據末尾。 因為你沒有初始化numbers
,它讀取在那里通過默認的垃圾值。 那是另一個很好的教訓: 始終初始化變量 。
您還會在管理x
和c
的方式上遇到問題。 僅當scanf
從用戶成功轉換十進制后,才應更新c
。 scanf
會在返回時提供成功的轉換次數。 您需要使用return檢查用戶輸入的有效十進制,然后僅在成功轉換后更新c
(而不是用戶輸入y/n
。
稍微整理一下,最好將邏輯稍微重新排列為類似以下內容:
#include <stdio.h>
int main (void) {
int numbers[100] = { 0 };
int c = 0;
int i = 0;
char answer[30] = { 0 };
printf (" Please insert a value: ");
GO:
if (scanf ("%d", &numbers[c]) == 1)
c++;
getchar ();
printf (" Do you want to add another value (y/n)? ");
scanf ("%c", answer);
if (*answer == 'y') {
printf (" Please insert another value: ");
goto GO;
}
for (i = 0; i < c; i++) {
printf (" number[%2d] : %d\n", i, numbers[i]);
}
return 0;
}
輸出量
$ ./bin/go
Please insert a value: 10
Do you want to add another value (y/n)? y
Please insert another value: 11
Do you want to add another value (y/n)? y
Please insert another value: 12
Do you want to add another value (y/n)? n
number[ 0] : 10
number[ 1] : 11
number[ 2] : 12
(注意:我將x
更改為i
迭代i
感覺更正常)
由於未初始化c
並且您將其用作“索引”( &numbers[c]
),因此該行為是不確定的。 這也可能會導致分段錯誤,甚至會按您預期的方式運行。
您需要做的就是在一開始就將c
設置為0。
另外,除非有確鑿的理由使用goto
否則請盡量避免使用goto
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.