Saturday, May 9, 2009

C++ Pointers to Strings?

I'm writing a C++ program in 3 separate files. Here's some of the pseudocode:





Rectangle.h


_________





...


private *char name;





rectangle


deconstructor


getName


setName


draw











Rectangle.cpp


_________





default constructor: name = "bleh";


constructor: [asks the user to enter a name and prints it back]


draw: [print name]


getName: gets the name


setName: modifies the name


deconstructor: deletes the string








TestRectangle.cpp


___________





...


Rectangle r1;


r1.draw();


r1.getName();





How do I... er... do all of this? I have to allocate memory for the string using the new keyword.


I've been trying to look this stuff up but can't seem to find anything helpful.

C++ Pointers to Strings?
"Algorithms + Data Structures = Programs", by Wirth.





You evidently learned C++ before you learned programming. Take a break and learn programming now.


C++ Pointers; Can someone use illustrations and explain?

Can someone give a simple explanation of the use of Pointers, how they work, and their purpose. Illustrations would be a +.

C++ Pointers; Can someone use illustrations and explain?
What are pointers?





Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes—of various sizes—at a local bank. Each safety deposit box will have a number associated with it, so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box.





Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelery. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables.





The cool thing is that once you can talk about the address of a variable, you'll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want to pass into a function, it's a lot easier to pass its location to the function than to copy every element of the data! Moreover, if you need more memory for your program, you can request more memory from the system—how do you get "back" that memory? The system tells you where it is located in memory. In other words, you get a memory address back. And you need pointers to store the memory address.





A note about terms: the word pointer can refer either to a memory address itself, or to a variable that stores a memory address. Usually, the distinction isn't really that important: if you pass a pointer variable into a function, you're passing the value stored in the pointer—the memory address. When some people want to talk about a memory address, they refer to it as a memory address. When they want a variable that stores a memory address, they call it a pointer. When a variable stores the address of another variable, they say that it is "pointing to" that variable.


___________





Pointer Syntax


___________





Pointers require a bit of new syntax because when you have a pointer, you need the ability to request both the memory location it stores and the value stored at that memory location. Moreover, since pointers are somewhat special, you need to tell the compiler when you declare your pointer variable that the variable is a pointer, and tell the compiler what type of memory it points to.





The pointer declaration looks like this:





%26lt;variable_type%26gt; *%26lt;name%26gt;;





For example, you could declare a pointer that stores the address of an integer with the following syntax:





int *pointer1; // points to an integer





Notice the use of the *. This is the key to declaring a pointer; if you add it directly before the variable name, it will declare the variable to be a pointer.





Important: if you declare multiple pointers on the same line, you must precede each of them with an asterisk:





// one pointer, one regular int


int *pointer1, non_pointer1;





// two pointers


int *pointer1, *pointer2;





As I mentioned, there are two ways to use the pointer to access information: it is possible to have it give the actual address to another variable. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is 'dereferencing the pointer.' Basically, you're taking the reference to some memory address and following it, to retrieve the actual value. It can be tricky to keep track of when you should add the asterisk. Remember that the pointer's natural use is to store a memory address; so when you use the pointer, i.e., pointer1, then, it evaluates to the address. You have to add something extra—the asterisk (*pointer1)—in order to retrieve the value stored at the address. You'll probably do that an awful lot. Nevertheless, the pointer itself is supposed to store an address, so when you use the bare pointer, you get that address back.





Pointing to Something: Retrieving an Address





In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of a variable (its location in memory), put the %26amp; sign in front of the variable name. This makes it give its address. This is called the address-of operator, because it returns the memory address.





Conveniently, both ampersand and address-of start with 'a;' that's a useful way to remember that you use %26amp; to get the address of a variable.





For example:





#include %26lt;iostream%26gt;





using namespace std;





int main()


{


int x; // A normal integer


int *p; // A pointer to an integer





p = %26amp;x; // Read it, "assign the address of x to p"


cin%26gt;%26gt; x; // Put a value in x, we could also use *p here


cin.ignore();


cout%26lt;%26lt; *p %26lt;%26lt;"\n"; // Note the use of the * to get the value


cin.get();


}





The cout outputs the value stored in x. Why is that? Well, let's look at the code. The integer is called x. A pointer to an integer is then defined as p. Then it stores the memory location of x in pointer by using the address-of operator (%26amp;) to get the address of the variable. Using the ampersand is a bit like looking at the label on the safety deposit box to see its number rather than looking inside the box, to get what it stores. The user then inputs a number that is stored in the variable x; remember, this is the same location that is pointed to by p.





The next line then passes *p into cout. *p performs the "dereferencing" operation on p; it looks at the address stored in p, and goes to that address and returns the value. This is similar to looking inside a safety deposit box only to find the number of (and, presumably, the key to ) another box, which you then open.





Notice that in the above example, pointer is initialized to point to a specific memory address—before it is used. If this was not the case, it could be pointing to anything. This can lead to extremely unpleasant consequences to the program. For instance, the operating system will probably prevent you from accessing memory that it knows your program doesn't own: or else, your program would crash. If it let you use unowned memory, you could mess with the memory of any running program. For example, if you had a document opened in Word, you could change the text! Fortunately, Windows and other modern operating systems will stop you from accessing that memory—by causing your program to crash. To avoid crashing your program, you should always initialize pointers before you use them.





[Side note: It is also possible to initialize pointers using free memory. This allows dynamic allocation of array memory. It is most useful for setting up structures called linked lists.]





The keyword 'new' is used to initialize pointers with memory from free store (a section of memory available to all programs). The syntax looks like the example:





int *ptr = new int;





It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder should free this memory at the end of its usage.





The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example:





delete ptr;





After deleting a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer, the pointer becomes a null pointer, in other words, it points to nothing. By doing this, when you do something foolish with the pointer, you find out immediately—instead of later, when you have done considerable damage.





In fact, the concept of the null pointer is frequently used as a way of indicating a problem—for instance, some functions left over from C return 0 if they cannot correctly allocate memory (notably, the malloc function).


A program in C++ pointers.?

please help me write a program to search for a given character and print the streing from the point of match using pointers.





i know to do it without pointers but i am asked by my sir to do it using pointers. please help me. you wouldn't be doing my home work but really helping me......


please help

A program in C++ pointers.?
First things first, 'char * s' is the same as the character array 'char s[].' In this example, s is what is commonly called a c-style string, which is a null-terminated array of characters.





For example, if you use the string 'cat', the c-string would be the character array {'c','a','t',0 (the number zero, not the character zero)}.





Just to note, c-strings can be initialized easily like this:


char s[] = "cat";





As I said before, char * s is the same as char s[] and they are interchangeable. In both cases, s points to the address of the first element of the array. When you say s[index], you are getting the value of the object at memory location s + index. You can do the same thing with pointers by first adding index to s and then dereferencing s, like so: *(s+index). This is what is going on in this example.





Lets say we're using the string 'cat' and the character we're looking for is 'a'. So this algorithm starts off with 'cat' being stored in a null-terminated character array s.





%26gt;while((c!=*s) %26amp;%26amp; (*s)){





This will loop as long as the character at s in not equal to character c and while the character at s in not equal to zero. For our first iteration, s is still pointing to the first character of the string and by dereferencing s (via *s) we get the character 'c'. Since this is neither equal to the character stored in c, 'a', nor is it equal to zero, we will continue.





When the end of the string is reached and s points to the null-terminating character, zero, the while loop will end because in C a value of zero is the same as false.





%26gt;s++; }





This increments the pointer, essentially behaving as an iterator. When you increment a pointer, it then points to the next character in the array, which in our case would be 'a'. Also note that the string represented by c-strings go from the character the pointer points to the null-character, so doing this effectively removes the first character and makes the string 'at'.





After s is incremented, the next iteration will exit the while loop because now *s = 'a'





%26gt;return s;





this obviously returns s, which now points to the c-string 'at'.





To hide the confusing parts of pointers, you could also do it like this:





int index = 0;


while( s[index] != c %26amp;%26amp; s[index] ) {


index++;


}


return s;





This method still uses pointers, except they are referenced in a more easily understood way.





Pointers are a very important topic. They may seem difficult or confusing at first, but once you get the hang of them they can be a very powerful and useful tool that will make your life much much easier.
Reply:const char * strchr(const char *s, char c)


{


char c2;





for (const char *p = s; (c2 = *p) != 0; ++p)


if (c2 == c) return p;





return null;


}


C++ pointers and 2D arrays?

please read the code and help me out


while allocating space for 2D arrays using new to read the elements





int * val=new int[r*c] // r and c are no of rows and columns resp.





for(int i=0; i%26lt;r; i++)


{


for(int j=0; j%26lt;c; j++)


{


cin%26gt;%26gt;val[i*c+j]; // what does this statement do?


}


}





my doubt is why not A[i] [j]?


what does this statement do?

C++ pointers and 2D arrays?
You haven't actually allocated a 2d array: you've allocated a 1d array of size r*c.





Consequently, you need to do some math to convert your 2d coordinate into a 1d index. i*c+j converts your (r,c) coordinate into a unique index. You can see how this works simply by trying various numbers:


(0, 0) = 0*c+0 = 0


(1, 0) = 0*c +1 = 1


(0, 1) = 1*c + 0 = c


(1, 1) = 1*c+1 = c + 1





In this way, every possible 2d coordinate gets mapped to an index between 0 and r*c.
Reply:The statement assigns the user input to the array in the position indicated by i, c+j.

snow of june

C/C++ pointers as strings?

I am a relative novice at C++, and I am trying to write a stack class that holds lines of text. I need to hold everything in pointers because I don't know the sizes of things, and I have one question. Do you have to use new or malloc to allocate adequate memory to a pointer, or will it act intelligently? For example will:





char *string = new char;


std::cin %26gt;%26gt; string;





instead of:





char *string = new char[100];


std::cin %26gt;%26gt; string;





possibly cause it to segfault or corrupt other variables (I know it will at least hold the data)? I haven't had that happen before, but just to make sure...

C/C++ pointers as strings?
the above answer is excellent advice (or below, the guy who said use strings). Do NOT use arrays of chars. You risk buffer overflow and if that happens your program will be entirely compromised. A buffer overflow in your case would be when you had a char array of say 100, but the user entered a line of text with over 100 chars. After 100, you're program will be writing char values to memory that is outside of your array and could be other variables, return values, etc.
Reply:Hi,


If u r using char pointers then dont worry about the size of string, to be saved in that char pointer.





Poiter reuires 2 bytes only. Char pointer holds only the address of the string not the string itself.





so


char *p;


p="a";


or


p="abcdefghijklmnopqrstuvwxyz";





so either u save a character or a string of any length, doesnt matter.
Reply:These examples do not make sense to me. 'char' is a primitive type and not a class.





This is how I would declare string. It is a simple array of char big enough for what you will use it for.





char string[100];


std::cin %26gt;%26gt; string;





If you use the C++ string class then it will resize and do clever things automatically. Hurrah!





#include %26lt;string%26gt;





string mystring;


std::cin %26gt;%26gt; mystring;


std::cout %26lt;%26lt; mystring;


C++ Pointers?

Say you know a memory location address (say 0x22ff70) and you want to know what is stored there (if anything), how do you go about printing the contents on screen?

C++ Pointers?
Casting, that is the magic of C++.





Try these articles.





http://www.boost.org/libs/conversion/cas...





http://en.wikipedia.org/wiki/Pointer





http://www.informit.com/guides/content.a...





Good luck
Reply:U can store this address in a pointer. Get the value thro' *


I think its correct. I studied this long back. Sorry if am wrong
Reply:If you want to print the valud of a variable you "Printf("%i",varr). (For example)





If its a pointer you have to "Printff("%i";%26amp;point). You have to tell the printing function to print not the value of the pointer (0x22ff70 in this case) but the value of the address the pointer points :).
Reply:If you know exactly data type kept at this address, do the following:


...


known_data_type * ptr = (known_data_type) void_pointer;


// print your known data here...


...





In another case, you cah just cast this address to char* or unsigned char * and get some dump:


...


unsigned char * up = (unsigned char *) void_pointer;


dump( up, any_size_you_need_if you_know_it);


C++ pointers?

im currently try to teach myself c++ my question is about pointers i understand how to use but i don't get why you would use them what dose it matter where something is stored in the memory or that you can access the things its pointing to by putting a * in front of it why wouldn't you just manipulate the object directly or am i missing something here? thanks

C++ pointers?
You have come upon a very complex thing. Pointers give the best of us headaches.





They aid in memory improvements, and they can allow a program to change large amounts of information "on-the-fly"





If you are not working on Operating Systems, or working on large programs, then you don't need to worry about it. That's the short of it.





I've never had to use them myself because what I am trying to do is not that big.





Hope that helps.
Reply:C++ began as a superset of C. Whether it is still a superset of C is debated, but it is probably not a separate language: you can access C's libraries and include files in a C++ program and also any of its design features.





The big advantage comes when you don't know how much data you are going to be working with and won't know until run-time. With a corporate database, for example, a company is always looking for new customers, and some customers move on. While some companies can do very well with a database which fixes a maximum size for the number of records they use, it's easier to use new CustomerRecord workrecord and delete workrecord on an as-needed basis. In other words, you code an algorithm for increasing and decreasing the size of the database rather than hard coding the size of the database into your program.





My background is in C. I haven't totally made the conceptual shift to C++ (though I don't have a problem with objects) and I don't want to.





Part of C's design specifications is that everything is passed by value except arrays. In other words when you send an int, float or other variable to a function, it creates a new variable, assigns it the same value as the variable it was sent, and works with that, not with the old variable. When the function ends control passes back to the calling function where the changes and manipulations you made have no effect. In C the only way to pass by reference is to send a pointer to the memory address where the value you want to change is stored. The compiler still creates a new variable, but since it only stores the memory address, its destruction when it goes out of scope will not cause the value at the end of the function to revert to what it was before. C++ does have a pass-by-reference operator, which is the same as the address-of operator in C: %26amp;. While it does make things a little more convenient for a hurried programmer, it also makes writing bad code a little easier, so not everyone uses it. Why make it easy when you should be thinking very hard about what you are doing with it anyhow?
Reply:One of the advantages of pointers are when u want to use an array as an argument of a function. if u give the array itself to the function %26amp; change it in the function, there will be no change in the main array but when you give the pointer of that array as the argument, changes will happen directly on your array %26amp; this is a very important use in programming! If not satisfied u can ask me for more !