GIDForums

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read


 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 24-Mar-2008, 23:48
hira hira is offline
Junior Member
 
Join Date: Nov 2007
Posts: 47
hira is on a distinguished road

Another pointer problem!


Hello everyone!

This program is supposed to reverse a string of characters using pointers alone. No new character array. It should work (coz its not my logic, but my teacher's) but I am not very good at pointer syntax at the moment. So could anyone please point out whats wrong. It is giving an "assertion error", I am not very clear what that is either (no compiling errors).

CPP / C++ / C Code:
#include<iostream>
#include<string>
#include<iomanip>
#include<cstring>

using namespace std;


void Reverse (char *str);


int main()
{
	char *str;
    str=new char [5];

	cout<<"Enter characters"<<endl;
	cin.getline (str, 5);
    

	Reverse (str);

	cout<<*str;

	delete [] str;
       
	return 0;
}



void Reverse (char *str)
{
	char *start, *end;
	char temp;

	start=str;
	end=str+(strlen(str) - 1);

		while (start<end)
		{
			temp=*start;
			*start=*end;
			*end=temp;

			start++;

			end--;
		}

		delete start;
		delete end;
}
  #2  
Old 25-Mar-2008, 01:20
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 353
Peter_APIIT is on a distinguished road

Re: Another pointer problem!


OK. I found the problem which is you delete start and end but didn't request it from heap memory.

delete start;
delete end;

One new one delete.
__________________
Linux is the best OS in the world.
  #3  
Old 25-Mar-2008, 01:38
hira hira is offline
Junior Member
 
Join Date: Nov 2007
Posts: 47
hira is on a distinguished road

Re: Another pointer problem!


Thanks Peter!

You mean I didn't initialize?
  #4  
Old 25-Mar-2008, 07:26
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,527
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Another pointer problem!


Quote:
Originally Posted by hira
You mean I didn't initialize?

No, he means that you should never apply the delete operator to something you didn't get from the new operator.

Regards,

Dave
  #5  
Old 25-Mar-2008, 07:44
hira hira is offline
Junior Member
 
Join Date: Nov 2007
Posts: 47
hira is on a distinguished road

Re: Another pointer problem!


So I should remove the delete statements? How else do you deallocate them?

I just compiled it without using them and it works correctly! Thanks dave and Peter!

My theoretical knowledge of pointers isn't good anyone, so could you tell me what wrong with this code (for output)

CPP / C++ / C Code:
for (int i=0;i<5;i++)
	{

	cout<<*str[i];

	}

If you don't write append a star to str[i], then the program works perfectly. I thought * referred to the content of a pointer, so why doesn't it work?
  #6  
Old 25-Mar-2008, 08:55
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,527
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Another pointer problem!


Quote:
Originally Posted by hira
So I should remove the delete statements?
Yes
Quote:
Originally Posted by hira
How else do you deallocate them?
You don't. Any variables that are declared (not allocated with new) in a function (or other program block) are automatically de-allocated when the program returns from that function (or leaves that program block).
Quote:
Originally Posted by hira
...could you tell me what wrong with this code...

str is the name of an array of chars. Element number i is accessed with the notation str[i]. Since str[i] is not a pointer, it is illegal to dereference it. See Footnote.

So the loop might look like:
CPP / C++ / C Code:
    for (int i = 0; i < 5; i++)
    {
        cout << str[i];
    }

Now whether that does what you want it to do is something else, but it is, at least, legal C++ code.


Regards,

Dave

Footnote:

If p is a pointer data type and i is an integer data type, the following two notations are identical:

CPP / C++ / C Code:
p[i]

is the same as

CPP / C++ / C Code:
*(p+i)

Now, if p is the name of an array, then the compiler treats it as a constant pointer whose value is the address of the first element of the array, so the above two expressions are valid (and they are equivalent to each other) whether p has been declared to be a pointer to char or an array of char.

Note that I am not saying that pointers are the same as arrays. They are not. It's just notation.
  #7  
Old 25-Mar-2008, 09:29
hira hira is offline
Junior Member
 
Join Date: Nov 2007
Posts: 47
hira is on a distinguished road

Re: Another pointer problem!


Thanks Dave for the explanation!

But aren't they almost interchangeable? Pointers and arrays.

I was having one more problem with the same code. When I edit it to be able to vary the size of the string, it doesn't work. Gives me that Microsoft Error: pointer.exe has encountered a problem etc. Why is that happening?

Here is the edited code:
CPP / C++ / C Code:
#include<iostream>
#include<string>
#include<iomanip>
#include<cstring>

using namespace std;


void Reverse (char *str);


int main()
{
	char *str;
	int a;
	str=new char [a];

    cout<<"Enter size"<<endl;
	cin>>a;
 
	cout<<"Enter characters"<<endl;
	cin.getline (str, a);
    

	Reverse (str);

	delete [] str;
       
	return 0;
}



void Reverse (char *str)
{
	char *start, *end;
	char temp;

	start=str;
	end=str+(strlen(str) - 1);

		while (start<end) //Swap start and end, then decrement to swap the adjacent characters and so on.
		{
			temp=*start;
			*start=*end;
			*end=temp;

			start++;

			end--;
		}

		
	cout<<endl<<"Reversed characters=";

	for (int i=0;i<5;i++)// Output
	{

	cout<<str[i]<<" ";

	}

	

}
  #8  
Old 25-Mar-2008, 10:44
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,527
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Another pointer problem!


Quote:
Originally Posted by hira
...But aren't they almost interchangeable? Pointers and arrays.
No. Pointers and arrays in C (C++, too) are not interchangeable or almost interchangeable. Not now. Not in a million years. Not ever. Now, there is some notation that can be used with either, since the name of an array is treated by the compiler as a constant pointer whose value is the address of the first element of the array.

However...

When you declare an array, you have a certain amount of storage. You can put stuff in that storage and you can get the same stuff back out, as long as nothing else in your program writes to that storage (accidentally or on purpose).

A pointer is a variable. If you give it a value that points to some storage for which your program has legal access, you can dereference that variable to put stuff in that storage and get the same stuff back out, as long as nothing else in your program writes to that storage (accidentally or on purpose).

You can set the value of a pointer variable to anything, but you can legally dereference it only if its value is the address of some storage for which your program has legal access.

So you can assign the value of a pointer to legal memory by using the new operator to get a block of memory from the system. You can assign the value of a pointer by setting it equal to the address of a member of an array that you have declared (or the address of any other variable currently in scope). You can do arithmetic on that variable's value. So, if a pointer has a value that is the address of an element of an array, and if you increment the pointer value, its value is the address of the next element in the array (assuming you haven't incremented it to point beyond the end of the array).

Once the pointer is set to some legal memory address, you can access that memory using pointer notation, such as *p = x; or you can use array notation, such as p[0] = x; Both notations mean exactly the same thing. (Not "almost," not "usually," not "nearly the same as," but exactly.)
Quote:
Originally Posted by hira
I was having one more problem with the same code....
Here is the edited code:
CPP / C++ / C Code:
	char *str;
	int a;
	str=new char [a];


The variable a is uninitialized. Its value is undefined, so the amount of memory that the new operator gives is unknown. Maybe it's big enough to hold what you want it to, or maybe not. Dereferencing str is undefined behavior. (Could cause a program crash; could appear to "work"; could do just about anything.)

If I were going to implement the program similar to your example, my main() might look something like this:
CPP / C++ / C Code:
int main()
{
    char *str;
    int a;

    cout << "Enter size" << endl;
    cin  >> a;
    if (cin.fail() || (a < 1)){ 
        cout << "Invalid entry" << endl;
        return 0;
    }
    while (cin.get() != '\n') // an "empty" loop to flush the input buffer since getline needs to start fresh
        ;

    str = new char[a];

    cout << "Enter characters" << endl;
    cin.getline(str, a); // note that it gets at most a-1 characters

    Reverse(str);

    delete [] str;

    return 0;
}


Regards,

Dave

Footnote: When you use the name of an array as a function argument, what is actually passed to the function is a pointer whose value is the address of the first element of the array.

The function itself has absolutely no way (no way) of knowing whether the thing refers to an array or some pointer whose value was obtained from new. If you call the function with the name of an array, the function has no way (no way) of knowing the size of the array unless you tell it (either with another integer data type argument or by using "global" variable or #define statement). There is no way to define a function that operates on an array so that the function can know the size of the array unless you tell it. The function always will be working on a pointer whose value was passed to it from the calling function. Yes, always.

Your Reverse function could have been defined and declared as
CPP / C++ / C Code:
void Reverse (char *str)

There is absolutely no difference (really!) between this and the declaration
CPP / C++ / C Code:
void Reverse (char str[])

That's right, no difference! But that still doesn't mean that arrays are "almost interchangeable" with pointers. It's just notation.
  #9  
Old 26-Mar-2008, 08:16
hira hira is offline
Junior Member
 
Join Date: Nov 2007
Posts: 47
hira is on a distinguished road

Re: Another pointer problem!


Thanks a lot Dave! You cleared so much up!

So a pointer itself points to the first element of the array, and when you increment it, it points to the next element and so on?

With regards to the function not able to know the size, why is it then working correctly right now, without being given the size?
  #10  
Old 26-Mar-2008, 08:44
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,527
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Another pointer problem!


Quote:
Originally Posted by hira
...a pointer itself points to the first element of the array, and when you increment it, it points to the next element and so on?
That is correct, and is of fundamental importance in your understanding of pointers and how they are used in C and C++ programs.
Quote:
Originally Posted by hira
With regards to the function not able to know the size, why is it then working correctly right now, without being given the size?
Nothing in the function Reverse depends on knowing the size of the array. It depends on the array having contents that can be properly processed by the standard library function strlen(). Namely, that there is a zero-byte terminated sequence of chars starting at the address pointed to by the value of its parameter that was passed from the calling function. That's what the getline() function put there. That's how cin.getline() works, and it wouldn't be nearly as useful if it didn't. All of these library functions are designed to work together.

A common use of arrays of chars is to hold so-called "C-style strings." All of the problems with knowing of the array and making sure it is large enough to handle your particular "string" are reduced, if not completely eliminated by using C++ standard library std::string objects.

In my opinion, for the vast majority of C++ applications, std::string objects are more appropriate than the legacy "C-style strings" consisting of zero-byte terminated sequences of chars (in an array of chars). After you cover the std::string class, you may not want to use "C-style strings" in arrays of chars any more. I mean, you still should know about and understand "C-style strings," for a number of reasons, but, in my opinion, std::string objects are (usually) the way to go. You won't have to worry with new or delete. It's done automatically!


Regards,

Dave
 

Recent GIDBlogNew Corolla Altis, 10th Generation - Part I by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Return pointer to template's nested class problem Kimmo CPP / C++ Forum 2 20-Sep-2007 23:39
Pointer Problem Esam CPP / C++ Forum 1 22-May-2006 15:39
[Tutorial] Pointers in C (Part II) Stack Overflow C Programming Language 0 27-Apr-2005 17:36
Please help! Newbie pointer problem! robsmith C Programming Language 5 12-Mar-2005 04:48

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 15:33.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.