Solved

Why this code gives ascii codes using pointers.

Posted on 2013-12-24
3
245 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
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 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 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.

862 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now