Указатели в C/C++ для начинающих

Andrew Peace, “A Beginner's Guide to Pointers”, public translation into Russian from English More about this translation.

See also 100 similar translations

Another translations: into Ukrainian. Translate into another language.

Participants

Mr.ElectroNick2371 points
Someone.else409 points
unknown.userx33 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8 9

A Beginner's Guide to Pointers

Указатели в C/C++ для начинающих

History of edits (Latest: m0nhawk 3 years, 1 month ago) §

What Are Pointers?

Что такое указатели?

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

Pointers are basically the same as any other variable. However, what is different about them is that instead of containing actual data, they contain a pointer to the memory location where information can be found. This is a very important concept. Many programs and ideas rely on pointers as the basis of their design, linked lists for example.

Указатели — это те же переменные. Разница в том, что вместо того, чтобы хранить определенные данные, они хранят адрес (указатель), где данные могут быть найдены. Концептуально это очень важно. Многие программы и идеи зависят от указателей, как от основы их архитектуры, например, связанные списки (linked lists).

History of edits (Latest: voxpuibr 3 years, 1 month ago) §

Getting Started

Введение

History of edits (Latest: Mr.ElectroNick 3 years ago) §

How do I define a pointer? Well, the same as any other variable, except you add an asterisk before its name. So, for example, the following code creates two pointers, both of which point to an integer:

Как объявить указатель? Собственно, так же, как и любую другую переменную, но с добавлением звездочки перед именем переменной. Так, например, следующий код создает два указателя, которые указывают на целое число.

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

int* pNumberOne;

int *pNumberOne;

History of edits (Latest: m0nhawk 3 years, 1 month ago) §

int* pNumberTwo;

int *pNumberTwo;

History of edits (Latest: m0nhawk 3 years, 1 month ago) §

Notice the "p" prefix in front of the two variable names? This is a convention used to indicate that the variable is a pointer. Now, let's make these pointers actually point to something:

Обратили внимание на префикс "p" в обоих именах переменных? Это принятый способ обозначить, что переменная является указателем. Так называемая венгерская нотация. Теперь давайте сделаем так, чтобы указатели на что-нибудь указывали:

History of edits (Latest: m0nhawk 3 years, 1 month ago) §

pNumberOne = &some_number;

pNumberOne = &some_number;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

pNumberTwo = &some_other_number;

pNumberTwo = &some_other_number;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

The & (ampersand) sign should be read as "the address of" and causes the address in memory of a variable to be returned, instead of the variable itself. So, in this example, pNumberOne is set to equal the address of some_number, so pNumberOne now points to some_number.

Знак & (амперсанд) следует читать как "адрес переменной ..." и означает адрес переменной в памяти, который будет возвращен вместо значения самой переменной. Итак, в этом примере pNumberOne установлен и содержит адрес переменной some_number, также pNumberOne указывает на some_number.

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

Now if we want to refer to the address of some_number, we can use pNumberOne. If we want to refer to the value of some_number from pNumberOne, we would have to say *pNumberOne. The * dereferences the pointer and should be read as "the memory location pointed to by," unless in a declaration, as in the line int *pNumber.

Таким образом, если мы хотим получить адрес переменной some_number, мы можем использовать pNumberOne. Если мы хотим получить значение переменной some_number через pNumberOne, нужно добавить звездочку (*) перед pNumberOne (*pNumberOne). Звездочка (*) разыменовывает (превращает в саму переменную) указатель и должна читаться как "место в памяти, которое указывается через ...", кроме объявлений, как в строке int *pNumber.

History of edits (Latest: ventalf 3 years ago) §

What We've Learned So Far: An Example

Чему мы научились: Пример

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

Phew! That's a lot to take in. I'd recommend that if you don't understand any of those concepts, to give it another read through. Pointers are a complex subject and it can take a while to master them. Here is an example that demonstrates the ideas discussed above. It is written in C, without the C++ extensions.

Фух! Многовато для начала, не правда ли? Я бы рекомендовал, если вы не понимаете то, что описано выше, перечитать ещё раз. Указатели - дело непростое и понимание их концепции может занять определенное время. Вот пример, который показывает идеи, изложенные выше. Пример написан на C, без дополнений C++.

History of edits (Latest: m0nhawk 3 years, 1 month ago) §

#include <stdio.h>

#include <stdio.h>

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

void main()

void main()

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

{

{

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

// declare the variables:

// объявляем переменные:

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

int nNumber;

int nNumber;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

int *pPointer;

int *pPointer;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

// now, give a value to them:

// инициализируем объявленные переменные:

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

nNumber = 15;

nNumber = 15;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

pPointer = &nNumber;

pPointer = &nNumber;

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §

// print out the value of nNumber:

// выводим значение переменной nNumber:

History of edits (Latest: Mr.ElectroNick 3 years, 2 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5 6 7 8 9

© Andrew Peace. License: The Code Project Open License (CPOL)