2

次のソースがあり、それを実行すると、値の符号が変更されます。どこが間違っているのかわかりません。どんな提案も役に立ちます

コード

#include <stdio.h>
#include <stdlib.h>
int arrsort(int *arr, int size);
int display(int *arr, int size);

int main()
{
    int s_o_1=0, s_o_2=0;
    int i; //index for arrays
    int a[s_o_1],b[s_o_2];


    printf("enter the size of the first array\n");
    scanf("%d",&s_o_1);

    printf("Enter the values of the first array\n");
    for (i=0;i<s_o_1;i++)
    {
        scanf("%d",&a[i]);
    }

    printf("enter the size of the second array\n");
    scanf("%d",&s_o_2);

    printf("Enter the values of the second array\n");
    for (i=0;i<s_o_2;i++)
    {
        scanf("%d",&b[i]);
    }

    //sort the first array

    arrsort(a,s_o_1);
    printf("The sorted first array is\n");
    display(a,s_o_1);

    //sort the second array

    arrsort(b,s_o_2);
    printf("The sorted second array is\n");
    display(b,s_o_2);

}

int arrsort(int *arr, int size)
{
    int temp; //for holding the temp value
    int i; //for indexing
    int j;

    for(j=0;j<size;j++)
    {
        for(i=0;i<size;i++)
        {
            if(arr[i]>arr[i+1])
            {
            temp=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=temp;
            }
        }   
    }
}



int display(int *arr, int size)
{
    int i; //array index
    for (i=0;i<size;i++)
    {
        printf("%d\t",i);

    }
    printf("\n");
    for (i=0;i<size;i++)
    {
        printf("%d\t",arr[i]);
    }
    printf("\n");
}

出力

enter the size of the first array
5
Enter the values of the first array
1 5 -10 -15 3
enter the size of the second array
5
Enter the values of the second array
-3 -5 15 9 10
The sorted first array is
0   1   2   3   4   
-15 -10 3   5   10  
The sorted second array is
0   1   2   3   4   
-15 -10 -5  -3  9   
4

3 に答える 3

2

問題は配列宣言です。

int s_o_1=0, s_o_2=0;
int i; //index for arrays
int a[s_o_1],b[s_o_2];

配列はおそらくサイズ0で宣言されています。適切な最大サイズで宣言するか、配列のサイズを読み取った後に宣言してください。

于 2012-11-14T08:33:21.493 に答える
1

コードの動作は未定義です。この行で:

int a[s_o_1],b[s_o_2];

サイズがゼロの配列を宣言します。後でs_o_1とs_o_2の値を取得しても、配列サイズは変更されません。したがって、すべての読み取りと書き込みは未定義の動作につながります。

C標準では、配列の長さがゼロ以外である必要があります。

于 2012-11-14T08:33:41.243 に答える
1

メモリを予約する方法が正しくありませんint a[s_o_1],b[s_o_2];

次のようなことをする必要がある場合はint *a, *b;、後で and を使用する必要があります 。同じことが b のメモリの割り当てにも当てはまります。scanf("%d",&s_o_1);a = (int*)malloc(sizeof(int)*s_o_1);

また、バブルソートアルゴリズムは以下のようなものでなければなりません

 for(j=0;j<size - 1;j++)
    {
        for(i=j + 1;i<size;i++)
        {
            if(arr[i]>arr[j])
            {
            temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
            }
        }   
    }
于 2012-11-14T08:38:32.853 に答える