C++ Pointers. Part 2

C ++ pointers, c ++ pointers

At the first part of the We have reviewed the, as using a pointer operator new You can allocate a piece of memory size required directly during the program operation. Just learned, as this memory can be freed, using delete. Saw how parameters are passed to a function pointer. And then, that it gives the opportunity to make changes in the value of variables, which are passed to the function.

We now look at an example where we pass to the function a pointer to a string (pointers of type char). This function returns a pointer to itself. Next task: there are two pointers to strings, under which they are allocated the necessary memory areas. It is necessary to combine these two strings. That is, it is necessary to allocate a new chunk of memory for the first string, to make it possible to add to it a second string.

Before, how to type code, that you are not “buried” errors – install the latest version of Microsoft Visual Studio environment. For example Microsoft Visual Studio 2013 Express. If you are using an earlier version, instead of functions strcat_s() apply strcat() and strcpy() instead strcpy_s().

Let's go in order. In string 4 It is a function prototype. Her task – allocate a new chunk of memory for the string, at the end of which it will write another string. This will be discussed below, when we come to the definition of this function,. Go to strings 11 – 12. They identify the variables, that will store the values ​​of the lengths of strings "string 1 " and "+ string 2". The length is calculated with the help of built-in functions strlen(). It will return the string length, excluding the symbol \0 . Therefore, when the initialization of variables strSize1 and strSize2 we add to that the return strlen(…) unit.

In string 14 defined pointer pStr1 on the first string. To write a string, you must first select it by memory: char* pStr1 = new char[strSize1]; The following copy a string in the allocated memory: strcpy_s(pStr1, strSize1, "string 1 "); . The first parameter, which receives function strcpy_s() – a pointer to the address where you want to copy a string; second – string size; the third – the string itself. The second pointer pStr2 We define exactly.

In str.. 20 – 21, Please show on screen the recorded strings. For this purpose it is enough to refer to them by name pointers. Pointer stores the address null cell. When we ask to show it on the screen – will be alternately displayed an array of characters (memory area, which was previously isolated), until it encounters an end-of-string character – \0 .

Str.. 23-24 – look how many bytes of memory takes each string. String 26 deleted a comment. It tried to add a second string to the first. Try to remove // and compile the program. Implementation of the program will abort error. You will see the following screen:

указатели на строки с++, pointers to the line c ++, new, deleteOf course – because the allocated memory area under the first string is too small, to append additional data. In string 28 write variable requiredSize really necessary memory size to record two strings: int requiredSize = (strSize1 + strSize2) - 1; Unit subtract because, variables that strSize1 and strSize2 already included two \0 , and we need only one.

Navigate to the definition of giveNewMem() – str.. 42 – 51. It will take the first string (a pointer to it) and integer (adequate memory size). Look – we need to allocate a new chunk of memory in this function for writing characters in it. So the function should return a pointer to the new memory location. So we can write in a pointer pStr1 new address, on which is located the memory to write two strings. Therefore, in the function header write so char* giveNewMem(char *pstr1, int reqSize)

So how will the new chunk of memory, then the memory, which occupies the first string should be released. If we do this right at the beginning of the function – data (characters string) disappear, because we lose the address at which they are located. Therefore, we should be in a function to request a new chunk of memory, in which we copy the characters of the first string, before you release the memory allocated for this component.

Create a new directory and immediately allocate memory for it, enough to accommodate two strings of symbols (str.. 44). Then copy the selected memory in the first string of characters: strcpy_s(strInFunc, reqSize, pstr1); The string is copied – you need to free up memory, that she was, lest there be a memory leak (str.. 48). We return from a function pointer to the new memory location: return strInFunc;

It turns out, when we call this function from main() (str.. 31) pStr1 = giveNewMem(pStr1, requiredSize); – in a pointer pStr1 written address of the new memory section, that can accommodate two strings. The only thing left to add this second string memory (str.. 33) and show it on the screen. Before exiting the program frees the memory. The first that has been allocated in the function, and then that is where the second string.

Compile program:

указатели на строки с++, pointers to the line c ++, new, delete

This example showed, as we, using pointers, can dispose of RAM with precision to the byte.

Summarize at the end and let the main, it is necessary to remember about pointers.

Why use pointers in C++?

  • using pointers, possible allocation of dynamic memory. Because memory for data is released in the course of the work program, and not at compile time. This is very beneficial, when we do not know in advance of the program will be used as actual data (variables). To allocate memory and free it, used by operators new and delete.
  • Indices are often used to access portions of the data volume of the functions. Character data and numerical arrays such as, which are defined outside the function. This approach came from the programming language C. In C ++, relative numeric variables and arrays easier to use link transmission. Soon we consider this topic. With strings in C style works best transfer by pointer.
  • using pointers – we work with the memory at the addresses directly. It's faster, than going by the name of variables.

Declaring pointers, taking addresses, dereferencing

Consider the example in detail:

In string 8 defined regular integer variable. In string 9 commented out declare and initialize the pointer. Try to remove the comment signs // and compile. We will report an error. All right. It should be a pointer to store the address (hexadecimal number), not the value (decimal number or symbol). In order for the, to get the address of a variable used by the capture operation addresses & (ampersand: Shift + 7). In string 10 create a pointer and write it the address of a variable:

инициализация указателя

To define a pointer, It is necessary to declare its type, for type an asterisk * and give it a name. Initialize the pointer can only address. If you do not assign an address pointer in its declaration, Initialize it to zero. Then this pointer will not be able to lead to complex errors, which is hard to find. He just anything will not indicate.

Usually we are not particularly interested, which stores an address pointer. We are interested in the data, located at this address. To view this data (or amend them) pointer to the name should apply the dereferencing operation. This is the same star *, as well as the declaration.

pointer dereference

Cout stream only is treated differently – not as much as in the pointer declaration. It helps to access data, stored at the address. This is shown in string 15 source.

In string 18 defined integral array five elements. Below specified pointer. Note – to initialize a pointer to the address array, operation & not applicable. This is because, that the name of the array refers to the address of the zero cell. It turns out that the record

pointer initialization

quite normally compiled. In the pointer variable pFirstArr address will be recorded zero array cell firstArr. This entry is similar to the following

pointer initialization

In string 25 shows an example of accessing data elements in the array through a pointer. Use array notation. That is, we do not need to apply the dereference operation, to access data in the array:

cout << "pfirstArr[0] = " << pFirstArr[0] << endl << endl;

Can, of course access the data array, using the notation of pointers, but it is inconvenient. Look, It looked as though assigning values to array elements and display values on screen:

Strings 27 – 28 source – definition C-strings and determination on this string pointer. Pointers are very good at working with strings. When we are in the stream cout call by name to a pointer to a character array, He will show us the entire string. As in the case of arrays, the compiler will display the characters on the screen, until it finds the end of the string in the array symbol \0

Look at the outcome of the program and the source code again. Try to understand how it works.

pointer initialization, pointer dereference, & taking addresses

Another digression, to encourage those, who is given difficult topic pointers :) You are not alone. Everything comes with practice! And it comes to you! Do not panic, if it looks too confusing for you. Solve as many as possible programming tasks. Even if you do something you do not in the process of writing code, our wonderful development environment will know about it.

Must see video about pointers (with the 12-th minute), if you haven't watched it in the first part of article:

Pointers, as parameters (arguments) function:

Newsletter of programming:

C++ Pointers. Part 2
4.8 (95%) 8 votes

9 thoughts on “C++ Pointers. Part 2

  1. Can not understand , in 15 string of code – strcpy_s(pStr1, strSize1, “string 1 “);
    function is used in strcpy_s 3 argument, earlier in the description of this function, it only indicates 2 argument (where the copy and that the copy).
    Actually the question : why it is now 3 argument? Because we're using a pointer as the first argument? Or because it is a new version of this feature (strcpy_s вместо strcpy)? Or this feature visual studio? unnecessarily. в code:: blocks the function strcpy takes 2 argument <>.

    1. The sample code used function strcpy_s(), instead of strcpy(), that really 2 argument. See the names attentively.

      P.S. This does not mean, so that should be done: strcpy_s() – function, not included in any POSIX standards, not C, or Linux, etc.. and so on. … and is used only on Windows operating systems (you do not even find its description in the literature). But this particular example – correct.

      1. I got just what I do not find the description of strcpy_s, And why this function, you need to know the size of the string is not clear.
        line size it is necessary to know because the first argument a pointer? Or is it a feature of the updated features? And how many arguments this function generally takes (can take) ?

    2. Specify the size of the copied string is very useful: if the row source, occasionally, as long as the receiver, you will receive a memory access error with the collapse of the entire application.

      See the description of the library and standard functions strncpy(), which is safer and increasingly used in professional code than strcpy().

  2. The development environment DEV CPP 5.11.
    The first example works without perevydeleniya memory function :)

  3. “The string is copied - you need to free up memory, that she was, lest there be a memory leak (str.. 48).”
    48:delete [] pstr1; // frees memory pstr1
    pstr1 pointer still immediately overwritten
    31:pStr1 = giveNewMem(pStr1, requiredSize);
    Normally Compile and executed without line 48.

Leave a Reply

Your email address will not be published. Required fields are marked *