Solved

Why this code gives ascii codes using pointers.

Posted on 2013-12-24
3
251 Views
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
0
Comment
Question by:searchsanjaysharma
3 Comments
 
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.

e.g.

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

0
 
LVL 33

Accepted Solution

by:
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:

(1)
char *str;
...
gets(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


(2)
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


(3)
*temp='\0';

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



(4)
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


Sara
0
 

Author Closing Comment

by:searchsanjaysharma
ID: 39771782
tx
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

809 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