简体   繁体   English

C 语言查询

[英]C language check

Can anybody check my code please?有人可以检查我的代码吗? i couldn't find the error or the misbehavior of my code.我找不到我的代码的错误或不当行为。 Note that when i assign a value for x inside the program everything goes well, but if i want the user to assign a value for x, the program doesn't work properly.请注意,当我在程序中为 x 赋值时一切顺利,但如果我希望用户为 x 赋值,程序将无法正常工作。 And sorry for my bad english.对不起我的英语不好。 Thank you!谢谢!

#include <stdio.h>
#include <string.h>

void sorting( int array[], int x){
    for (int i = 0; i < x-1; i++) // The (x-1) is because we are starting at index zero!!
    {
        for (int j = 0; j < x-1; j++)
        {
            if (array[j]>array[j+1])
            {
                int temp;
                temp=array[j];
                array[j]=array[j+1];
                array[j+1]=temp;
            }
        }
    }
}
void printing(int array[],int x) {
    printf("\nThe sorting is:\n");
    for (int i = 0; i < x; i++)
    {
        printf("%d,\t",array[i]);
    }
}

int main(){
    int x;
    int array[x];

    printf("Enter the size of your array as a natural no:\n");
    scanf("%d",&x);

    printf("Now enter %d nos to be arrange:\n" ,x);
    
    for (int i = 0; i < x; i++)
    {
        printf("Enter a no:\n");
        scanf("%d",&array[i]);
    }
    printf("The array of %d int no:\n",x);
    for (int i = 0; i < x; i++)
    {
        printf("%d,\t", array[i]);
    }
    
    sorting(array,x);
    printing(array,x);

    return 0;
}

//I tried to assign a value for x inside the program everything goes well, but if i want the user to assign a value for x, the program doesn't work properly.

You need to scan the x before array definition, otherwise x has undetermined value and you invoke U ndefied B ehaviour您需要在数组定义之前扫描x ,否则x具有未确定的值并且您调用U ndefied B行为

int main(){
    int x;
    int array[x];

    printf("Enter the size of your array as a natural no:\n");
    scanf("%d",&x);

=====> =====>

int main(){
    size_t x;

    printf("Enter the size of your array as a natural no:\n");
    if(scanf("%zu",&x) != 1 {/* handle scanf error */}

    int array[x];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM