[英]implementing bubble sort program in c
我只是在 c 中實現冒泡排序,但我必須面對從用戶那里獲取數組元素的問題,它沒有正確獲取,假設我輸入數組大小 5 之后我無法在數組中存儲 5 個元素,我寫了這段代碼主 function 內
#include<conio.h>
#include<stdio.h>
void bubbleSort(int *arr, int size) {
int temp, i, j;
for(i = 1; i < size; i++){
for(j = 0; j <= size - i -1 ; j++){
if(*(arr+j) > *(arr+j+1)) {
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1)= temp;
}
}
}
}
void display(int *p, int s) {
for(int i = 0; i < s; i++){
printf("%d, ", *(p+i));
}
}
int main() {
int i, size, arr[size];
printf("\n Enter Array Size ....");
scanf("%d", &size);
printf("\n Enter %d array values...", size);
for(i = 0; i < size; i++){
scanf("%d", &arr[i]);
}
bubbleSort(arr, size);
display(arr, size);
return 0;
}
如果您在打開警告的情況下運行編譯器(例如,在gcc中-Wall
將是一個選項。)您會看到類似於以下內容的警告:
Build Status (so.prj - Debug)
s0_15.c - 1 warning
25, 27 warning: variable 'size' is uninitialized when used here
25, 21 note: initialize the variable 'size' to silence this warning
Link so.exe
"c:\Play\so.exe" successfully created.
Build succeeded.
對此警告的最小修復是在使用它之前簡單地初始化變量size
......
int main(void) {
int i, size;
printf("\n Enter Array Size ....");
if(scanf("%d", &size) != 1) {/*handle error and leave*/ }
if(size <= 0){/*handle error and leave*/ }
int arr[size];//because this is a VLA, it cannot be
//initialized upon declaration...
memset(arr, 0, sizeof arr);//...so initialize here before using.
...
(請注意, VLA在使用 C99 時可用,並且從那時起可以在編譯器中定義。在嘗試這種方法之前,請閱讀您的編譯器文檔以了解。)
這是你的問題:
int i, size, arr[size];
當你聲明一個數組時,它的大小必須在聲明時知道——它要么是一個常量表達式(比如5
),要么是一個已經正確初始化或分配了一個好的值的變量。
此時, size
尚未初始化或賦值,其值為indeterminate 。 arr
將被調整為該值的大小,如果該值為 0 或負數,則行為將是未定義的。 無論您以后存儲什么size
,聲明后該大小都不會改變。
因此,您需要將arr
的聲明推遲到將值讀入size
之后:
int i, size;
printf("\n Enter Array Size ....");
scanf("%d", &size);
int arr[size];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.