Указатели в C+&plus

Содержание
Введение
Простой пример
Другие статьи о C++

Введение

В современном С++ использования указателей можно избежать во многих случаях.

Простейший пример

#include <iostream> using namespace std; /* Pointers */ int main() { int a = 5; int *px = &a; int *px2 = &a; //px is now an address in memory where variable a was stored cout << endl << "a = " << a; cout << endl << "pointer px: " << *px; // will show the value stored at this address cout << endl << "pointer px address: " << px; // will show the address in hex format cout << endl << "pointer px2 address: " << px2; a = 9; cout << endl << "a = " << a; cout << endl << "pointer px: " << *px; // will show the value stored at this address cout << endl << "pointer px address: " << px; // will show the address in hex format cout << endl << "pointer px2 address: " << px2; *px2 = 11; cout << endl << "a = " << a; cout << endl << "pointer px: " << *px; // will show the value stored at this address cout << endl << "pointer px address: " << px; // will show the address in hex format cout << endl << "pointer px2 address: " << px2; }

PS C:\Users\Andrei\cpp\SimpleCode\46> g++ .\46.cpp

PS C:\Users\Andrei\cpp\SimpleCode\46> .\a.exe a = 5 pointer px: 5 pointer px address: 0x7bfe0c pointer px2 address: 0x7bfe0c a = 9 pointer px: 9 pointer px address: 0x7bfe0c pointer px2 address: 0x7bfe0c a = 11 pointer px: 11 pointer px address: 0x7bfe0c pointer px2 address: 0x7bfe0c

#include <iostream> using namespace std; /* Pointers */ int main() { const int SIZE = 5; int arr[SIZE]{4,55,79,1,7}; for (int i = 0; i < SIZE; i++) { cout << arr[i] << endl; } // array name is a pointer to its first element int *pArr = arr; cout << "arr\t"<< arr << endl; cout << "pArr\t"<< pArr << endl; cout << "=============================" << endl; for (int i = 0; i < SIZE; i++) { cout << pArr[i] << endl; } cout << "=============================" << endl; // array is a continuous memory allocation // elements are going one by one without gaps in memory // that is why when we move pointer to the next value // we reach to the following array element for (int i = 0; i < SIZE; i++) { // by adding 1 here we are moving 4 bytes in the memory // because we have integer values cout << *(pArr + i) << endl; } cout << "=============================" << endl; for (int i = 0; i < SIZE; i++) { // using pointer to go through array cout << *(arr + i) << endl; } cout << "=============================" << endl; for (int i = 0; i < SIZE; i++) { // here we will get the memory addresses // note that the step is 4 bytes cout << (arr + i) << endl; } }

PS C:\Users\Andrei\cpp\SimpleCode\47> g++ .\47.cpp

4 55 79 1 7 arr 0x7bfde0 pArr 0x7bfde0 ============================= 4 55 79 1 7 ============================= 4 55 79 1 7 ============================= 4 1 7 ============================= 0x7bfde0 0x7bfde4 0x7bfde8 0x7bfdec 0x7bfdf0

Похожие статьи
Development на C++
Перегрузка функций
-c: Компиляция
Разбиение кода на части
Вектор
Классы
SFML
Тетрис на C++ с библиотекой SFML2
SDL
Массив Структур
Как узнать тип переменной C++
Решение задач на C++
Как создать пустую строку в C++
Запросы к REST API на C++
Ошибки C++

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: