次のコードをテストすると、セグメンテーション違反が発生し続けます。現在、ウェブを検索しても答えが見つかりません。
a = (byte *)malloc(sizeof(byte) * x ) ;
for( i = 0 ; i < x-1 ; i++ )
{
scanf("%d", &y ) ;
a[i] = y ;
}
y と x の両方が初期化されます。X は、ユーザーが決定した配列のサイズです。セグメンテーション違反は、最後から2番目に追加される整数にあります。これは、 printf("roar") を追加することで見つかりました。a[i] を y に設定し、一度に 1 つの数字を入力する前に。Byte は unsigned char の typedef です。
注:私も使ってみました
a[i] = (byte)y ;
A は次のように初期化されます
byte *a ;
コード全体を表示する必要がある場合は、次のとおりです。
#include <stdio.h>
#include <stdlib.h>
#include "sort.h"
int p_cmp_f () ;
int main( int argc, char *argv[] )
{
int x, y, i, choice ;
byte *a ;
while( choice !=2 )
{
printf( "Would you like to sort integers?\n1. Yes\n2. No\n" ) ;
scanf("%d", &choice ) ;
switch(choice)
{
case 1:
printf( "Enter the length of the array: " ) ;
scanf( "%d", &x ) ;
a = (byte *)malloc(sizeof( byte ) * x ) ;
printf( "Enter %d integers to add to the array: ", x ) ;
for( i = 0 ; i < x -1 ; i++ )
{
scanf( "%d", &y ) ;
a[i] = y ;
}
switch( choice )
{
case 1:
bubble_sort( a, x, sizeof(int), p_cmp_f ) ;
for( i = 0 ; i < x ; i++ )
printf( "%d", a[i] ;
break ;
case 2:
selection_sort( a, x, sizeof(int), p_cmp_f ) ;
for( i = 0 ; i < x; i++ )
printf( "%d", a[i] ;
break ;
case 3:
insertion_sort( a, x, sizeof(int), p_cmp_f ) ;
for( i = 0 ; i < x ; i++ )
printf( "%d", a[i] ;
break ;
case 4:
merge_sort( a, x, sizeof(int), p_cmp_f ) ;
for( i = 0 ; i < x ; i++ )
printf( "%d", a[i] ;
break ;
case 5:
quick_sort( a, x, sizeof(int), p_cmp_f ) ;
for( i = 0 ; i < x ; i++ )
printf( "%d", a[i] ;
break ;
default:
printf("Enter either 1,2,3,4, or 5" ) ;
break ;
}
case 2:
printf( "Thank you for using this program\n" ) ;
return 0 ;
break ;
default:
printf( "Enter either 1 or 2: " ) ;
break ;
}
}
free(a) ;
return 0 ;
}
int p_cmp_f( byte *element1, byte *element2 )
{
return *((int *)element1) - *((int *)element2) ;
}