根据字符串的长度对静态数组中的字符串进行排序会导致崩溃? |错误的分配/访问权限| [英] Sorting Strings in a static array based on their length crashes? |wrong allocation/access|

查看:96
本文介绍了根据字符串的长度对静态数组中的字符串进行排序会导致崩溃? |错误的分配/访问权限|的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个字符串数组,并根据它们的长度(最小->最大)对它们进行排序,但是程序在所有输入后都崩溃了.
并且绕过元素0(在输入过程中直接从元素1开始)

I wanted to make an array of strings and sort them in order based on their length (smallest -> biggest) but the program crashes after all inputs.
And also it bypasses Element 0 (starts directly from element 1 during input)

 #include <stdio.h>
    #include <stdlib.h>
    main()
    {
        int i,j,N;
        printf("\nInput amount of  alphanumericals: ");
        scanf("%d",&N);
            {
                int min;
                char *swap=(char*)malloc(sizeof(char)*150);
                char *A[N],**temp; 
                for(i=0;i<N;i++)
                    *(A+i)=malloc(sizeof(char)*N);//Error Here
                temp=A;
                for(i=0;i<N;i++){
                    printf("\nInput  %d element:",i+1); 
                    fgets(temp+i,150,stdin);//And Here
                }


    printf("\n\nData [");
    for(i=0;i<N;i++)
        printf(" %s",A[i]);
    printf(" ]\n\n");

    //insertion sort
    for(i=0;i<N;i++){
        min=i;
        for(j=i+1;j<N;j++){

            if(strcmp(A[j],A[min])<0){
                min=j;
            }

        }   
        if(min!=i){
            swap=A[i];
            A[i]=A[min];
            A[min]=swap;
        }   
    }
    free(swap);
    printf("\n\nInsertion Sorted Data [");
    for(i=0;i<N;i++)
        printf(" %s",A[i]);
    printf(" ]");
    }
return 0;
}

推荐答案

此错误:

 for(i=0;i<N;i++)
    *(A+i)=malloc(sizeof(char)*N);//Error Here

我是用g ++编译器复制的,如果您也是这种情况,即您也使用g ++进行编译,则将强制类型转换为char *:

i reproduced with g++ compiler, if this is your case also i.e. you also compiling with g++ add casting to char* :

*(A+i)= (char*) malloc(sizeof(char)*N);//Error Here

第二个问题是因为您尝试传递char **而不是char * 解决:

The second issue is because you trying to pass char** instead of char* fix :

fgets(*(temp+i),150,stdin);//And Here

在scanf(%d",& N);之后也加上括号.限制变量 min swap 的范围,因此以后的所有内容都不可见.

Also brackets after scanf("%d",&N); limits scope of variables min and swap , so later should not be visible at all.

这篇关于根据字符串的长度对静态数组中的字符串进行排序会导致崩溃? |错误的分配/访问权限|的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆