Solved

Why this code gives ascii codes using pointers.

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

Expert Comment

by:käµfm³d 👽
Comment Utility
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 32

Accepted Solution

by:
sarabande earned 500 total points
Comment Utility
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
Comment Utility
tx
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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 tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

771 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

10 Experts available now in Live!

Get 1:1 Help Now