arrays - why Segmentation fault error in this program in c? -


why dr segmentation fault in code? correct here, syntax ... etc.the program simple,just 2 sort content of 2 arrays third array; have taken 2 arrays array1 , array2 , third 1 array in sorting done.

#include<stdio.h>   int main() {     int array1[10] = {1, 2, 4,5,7,8,45,21,78,25};     int array2[5] = {3, 6, 9,15,17};     int array[20];     int i,j,temp;     int l1 = sizeof(array1)/sizeof(int);     int l2 = sizeof(array2)/sizeof(int);     int l3 = l1+l3;      (i = 0;i < l1; i++)      {         array[i]=array1[i];     }     (i = 0;i < l2; i++)      {         array[i+l1]=array2[i];     }     (i = 0;i < (l1+l2); i++)      {         printf("%d\n", array[i]);     }     printf("\nsorted array:\n");      for(i=0;i<l3;i++)     {         for(j=i;j<l3;j++)         {             if(array[i] > array[j])             {                 temp=array[i];                 array[i]=array[j];                 array[j]=temp;             }         }     }     (i = 0;i < l3; i++)      {         printf("%d\n", array[i]);     }      return 0; } 

because this not want:

int l3 = l1 + l3; 

it add known l1 arbitrary l3, giving larger arbitrary value. instead, should be:

int l3 = l1 + l2; 

the other, though relatively minor, problem have efficiency of algorithm, start , end conditions of loops. code:

for (i = 0; < l3; i++) {     (j = i; j < l3; j++) { 

has 2 problems. first, i loop goes far since know when it's @ l3 - 1, there no elements right. secondly, j loop starts @ i , know array[x] > array[x] can never true (x because i == j).

it better use:

for (i = 0; < l3 - 1; i++) {     (j = + 1; j < l3; j++) { 

to remove these inefficiencies.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -