Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Pointer Arithmetic




In C++ one can add an integer quantity to or subtract an integer quantity from a pointer. This is frequently used by programmers and is called pointer arithmetic. Pointer arithmetic is not the same as integer arithmetic, because the outcome depends on the size of the object pointed to.

For example, ptr++ causes the pointer to be incremented, but not by 1. It is incremented by the size of type, which it points to. ptr-- causes the pointer to be decremented, but also by the size of type, which it points to.

 

 

Another form of pointer arithmetic allowed in C++ involves subtracting two pointers of the same type. For example:

int *ptr1 = &nums[1];

int *ptr2 = &nums[3];

int n = ptr2 - ptr1; // n becomes 2

 

If we declare:

int a; / /variable a occupies in memory 4 bytes.

int *p = &a; / / p is a pointer to int, we can assign address of int variable a

Incrementation:

p++; // the value of p increases by 4 bytes

Decrementation:

p--; // the value of p decreases by 4 bytes

Addition:

p+=5; // the value of p increases by 4*5=20 bytes

On the whole, p+=x means that an address, which is the value of p, increases by x*sizeof(x) bytes. Standard function sizeof defines the size of variable or type, written in brackets.

Multiplication and division cannot be used in pointer arithmetic.




Поделиться с друзьями:


Дата добавления: 2014-01-11; Просмотров: 371; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.006 сек.