Segmentation fault while using insertion sort -


i try implement insertion algorithm calling insort function. somehow, along way made mistakes terminal print out segmentation faults. please help. thanks!

int  main(int argv,char *argc[]){     int a[argv-2];     for(int i=1;i<argv;i++){         a[i-1]=atoi(*(argc+i));     }     insort(&a,argv-1,0);     for(int i=0;i<argv-1;i++){         printf("%d",a[i]);     }     printf("\n");     return 0; }  int insort(int *a[],int size,int n){     int temp;     if(n<size){         for(int i=n;i>=0 && *(a+i)>*(a+i-1);i--){             temp=*(a+i-1);             *(a+i-1)=*(a+i);             *(a+i)=temp;         }     }     return insort(a,size,n++); }  

when compiling program, pay attention warnings compiler emits.

for each of warnings, have understand why given , how fix properly.

$ gcc -std=c99 insort.c insort.c:7:9: warning: implicit declaration of function 'atoi' [-wimplicit-function-declaration] insort.c:11:9: warning: implicit declaration of function 'printf' [-wimplicit-function-declaration] 

to fix these, insert following lines @ top:

#include <stdio.h> // printf #include <stdlib.h> // atoi 

the next one:

insort.c:10:5: warning: implicit declaration of function 'insort' [-wimplicit-function-declaration] 

to fix it, move whole insort function above main function.

the next one:

insort.c:23:17: warning: assignment makes integer pointer without cast 

this 1 bad. parameter int *a[] means int **a, pointer pointer int. fix this, remove square brackets.

the next one:

insort.c:22:12: warning: passing argument 1 of 'insort' incompatible pointer type 

the & operator not necessary. when pass array function, decays pointer beginning of array. remove &.

now, program compiles without giving warnings. that’s good. next level:

$ gcc -std=c99 -wall -wextra -os insort.c 

wow. these warnings enabled, compiler doesn’t complain anymore. that’s good.

(the -os optimization option necessary enable of warnings, since tested when compiler optimizes code.)

now program compiles. when running it, seems stuck in endless loop. worst errors fixed now.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -