Reputation: 109
I am trying to use the bubble sort method to organize a matrix. I am getting an error that says Segmentation fault (core dumped). I am programming on a Virtual Machine using Ubuntu and Codelite. Hope you can help me out.
This is the code.
#include <stdio.h>
#include <stdio.h>
#include <math.h>
int main(){
int tam, comp, var;
printf("Ingrese el tamano del array que va a crear:\n");
scanf("%d", tam);
int arr[tam];
printf("Ingrese los elementos del array:\n");
for(int i=0; i < tam; i++){
printf("Elemento arr%d", i+1);
scanf("%d", &arr[i]);
}
for(int j=0; j < tam; j++){
for(comp=0; comp<tam; comp++){
if(arr[comp]<arr[comp+1]){
var=arr[comp];
arr[comp]=arr[comp + 1];
arr[comp + 1]=var;
}
}
}
printf("La matriz en orden descendente es:\n");
for(int i=0; i < tam; i++){
printf("%d ", arr[i]);
}
}
Upvotes: 0
Views: 768
Reputation: 16540
the following proposed code:
stderr
Suggest using puts()
rather than printf()
for output that does not contain any formatting.
and now the proposed code:
#include <stdio.h> // printf(), scanf(), fprintf(), stderr
//#include <math.h> <<-- contents not used, so do not include
#include <stdlib.h> // exit(), EXIT_FAILURE
int main( void )
{
int tam;
printf( "Ingrese el tamano del array que va a crear:\n" );
if( 1 != scanf( "%d", &tam ) )
{
fprintf( stderr, "scanf for 'tam' failed\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
int arr[tam];
printf( "Ingrese los elementos del array:\n" );
for( int i=0; i < tam; i++ )
{
printf( "Elemento arr%d", i+1 );
if( 1 != scanf( "%d", &arr[i] ) )
{
fprintf( stderr, "scanf for array entry %d failed\n", i+1 );
exit( EXIT_FAILURE );
}
// implied else, scanf successful.
}
for( int j=0; j < tam; j++ )
{
for( int comp=0; comp < (tam-1); comp++ ) // note correction and data scope limiting
{
if( arr[comp] < arr[comp+1] )
{
int var = arr[comp]; // note data scope limiting
arr[comp] = arr[comp + 1];
arr[comp + 1] = var;
}
}
}
printf( "La matriz en orden descendente es:\n" );
for( int i=0; i < tam; i++ )
{
printf( "%d ", arr[i] );
}
}
Upvotes: 0