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 34

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

726 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