Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Why this code gives ascii codes using pointers.

Posted on 2013-12-24
Last Modified: 2014-01-10
I am writing a program of sorting a string with bubble sort using pointers. Works fine if len<9. But if len>9, it gives ascii values.

Why it is so.PTRSORT.CPP
Question by:searchsanjaysharma
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39738857
Are you certain that what you are doing is a bubble sort? All of the implementations that I have seen use simple swapping between two array elements rather than comparing a copy of the input to the original.


int sort(char* const str, const int strLength, char* result)
    int swapOccurred = true;

    if (result == NULL)
        return false;

    strncpy(result, str, strLength + 1);

    while (swapOccurred)
        swapOccurred = false;

        for (int i = 0; i < strLength - 1; i++)
            if (*(result + i + 1) < *(result + i))
                char c = *(result + i + 1);

                // SWAP
                *(result + i + 1) = *(result + i);
                *(result + i) = c;
                swapOccurred = true;

    return true;

Open in new window

LVL 33

Accepted Solution

sarabande earned 500 total points
ID: 39740388
for cpp file you would use the c++ compiler and c++ standard with stl (since 1998!!!). then, you should not use iostream.h, string.h, and malloc, because those were deprecated since more than 15 years. instead you include <iostream>, <string> (all without extension) and new operator instead of malloc in case you really would need to handle char arrays on the heap yourself what actually also shouldn't be done in c++.

because of the outdated coding you encounter some issues:

char *str;

Open in new window

here str is a pointer variable which has an undefined value. it could be NULL such that it points to nothing, but it also could contain some binary data which could be interpreted as a valid address or not. it is very likely that the gets call crashes because of this cause the gets wants to write the user input to the address given by str.

to make that safe you could do:

char str[1024]  = '\0';

Open in new window

what would provide a big and safe char buffer on the stack which is totaly empty.

using iostream classes from c++ standard you would do:

std::string str;
std::cout<<"///*** Program for sorting the string with bubble sort using pointers ***///";
std::cout<< std:.endl << "Enter the String: ";
std::getline(std::cin, str);

Open in new window

char *temp=(char*)malloc(sizeof(char)*len);

Open in new window

the buffer allocated by malloc was not big enough as it doesn't reserve an extra character for the zero termination. you would need to reserve len+1 characters for the temporary.

char* temp = new char[len+1];

Open in new window

a char always has size 1, so sizeof is not required. you would free the pointer by

delete []temp;

Open in new window

after use.

a simpler method would be to call strdup if you still think that c coding is easier (what surely is a wrong assessment).

char * temp = strdup(str); // cares for lenght and makes a copy of str using malloc

Open in new window


Open in new window

here your code is writing beyond allocated buffer because the temp is too short to take the final zero char.

note, allocating the temporary buffer and the two while loops for copying and rewinding the chara array are 18 statements which could be reduced to one by:

std::string temp = str;

Open in new window

the next nested loops are implementing a bubble sort which i can't actually fully verify if it is correct. the problem is that you always are incrementing and decrementing pointers instead of using indices and let the pointers as they are. kaufmed showed code for the bubble sort which uses pointer arithmetics (not necessary either, and i have doubts that the loop is not endless in some cases), but actually the simplest c code for that is like

for (int i = 0; i < str_length-1; ++i)
    for (int j = i+1; j < str_length; ++j)
          if ((str[i] > str[j]) // here you may cast to unsigned int to handle negative char codes
                var = str[i];
                str[i] = str[j];
                str[j] = var;

Open in new window

the bubble sort algorithm takes the first char str[ i ] of the still unsorted buffer and compares all following characters up to string length. if one of those is 'less' than the start character, both were swapped. finally at position i we have the minimum character code, such that we can go the next iteration.

if using c++ stl it would be much easier:

int main()
      std::getline(std::cin, str);
      if (!str.empty())
          std::sort(str.begin(), str.end());      

Open in new window


Author Closing Comment

ID: 39771782

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question