where is the run-time error in that code?

void main(){
....
char *fruites[5] = {"apple", "banana", "orange", "apricot", "pineapple"};
bubble(fruites,5,10);
}
 void bubble(char  *a[], int size, int columns)
 {
     int j,i;
     char * x= new char[columns];
     for (int z=0; z<columns;z++){
     *(x+z) ='0';

     }

         for (i = size - 1; i > 0; i--) {
                 for (j = 0; j < i; j++) {
                         if (strcmp(a[j],a[j+1]) > 0) {
                                 strcpy(x, a[j]);
                                 strcpy(a[j], a[j+1]);
                                 strcpy(a[j+1], x);
                         }
                 }
         }
 } // sorting

Recommended Answers

All 2 Replies

Anything you create in your code like this - "some letters" - you cannot write over. It is a string literal and is read-only. If you copy a string literal into a char array, you can of course then write over your own char array, but you cannot write over the actual memory containing that string literal. Since you're using C++, you would find this easier if you used C++ string objects.

While I'm here, void main() is just wrong. int main() is correct.

Declare it like this and it will work because the compiler copies each of the fruits into it's own 10-byte buffer that can be overwritten.

char fruites[5][10] = {"apple", "banana", "orange", "apricot", "pineapple"};

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.