理解Pointers In C++:第一重

2024-03-30 08:32
文章标签 c++ 理解 pointers 第一重

本文主要是介绍理解Pointers In C++:第一重,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • Variable vs. Pointer

int foo;
int *foo_ptr = &foo;

Grammatrically speaking, there is no such thing as a “pointer variable”: all variables are the same.

There are, however, variables with different types. foo's type is int. foo_ptr's type is int *.

The point of that is that “the pointer is not the variable!”. The pointer to foo is the contents of foo_ptr.

The pointer has a type, too, by the way. Its type is int. Thus it is an "int pointer" (a pointer to int : int *ptr).

An int **'s type is int * (it points to a pointer to int). The use of pointers to pointers is called multiple indirection.

  • Declaration syntax

  1. Multiple variables

    int *ptr_a, not_ptr_b;
    

    In this way, not_ptr_b is not a pointer. * operator belongs to the variable and not to the type, this is something that could be quite confusing.

  2. d

  • Initialization

A pointer needs to be initialized before its used if you don’t want it to use some other objects address.

When initializaing a pointer you do it with the new operator, this is called dynamic allocation as it is done in runtime and not compile time.

char * c = new char;   // dynamic alloc (one char)

A common mistake is thinking that you can use uninitialized pointers.

int *ip;
*ip = 12;   // Gives error! 

When you dynamically assign memory to objects you should be careful to return the memory by delete. If you don’t return memory it becomes a spaceleak in your program since no other object can now occupy the space you used.

delete c;	// deletes space pointer used
  • Assignment and pointers

foo_ptr = 42;

This is a wrong way. Compiler usually warn when you try to assign an int to a pointer variable. gcc will say “warning: initialization makes pointer from integer without a cast”.

  • Dereferencing (dereference operator *)

int bar = *foo_ptr;
*foo_ptr = 42; // store operation

The dereference operator * looks up the value that exists at an address.

  • Array vs. Pointers

int array[] = {45, 67, 89};
  1. decaying

    One neat feature of C is that, in most places, when you use the name array again, you will actually be using a pointer to its first element (in C temrs, &array[0]), this is called “decaying”: the array decays to a pointer.

    Decaying is an implicit &; array == &array == &array[0]. In English, these expressions read “array”, “pointer to array”, and “pointer to the first element of array” , the subscript operator [] has higher precedence than the address-of operator.

  2. Difference between array and pointer

    1. assigning to the name array
    2. passing it to the sizeof operator
  3. points

    1. passing an array to function

      When you pass an array as an argument to a function, you really pass a pointer to the array’s first element, because the array decays to a pointer. You can only give cout (which like printf in C) the pointer, not the whole array. This is why cout has no way to print an array: It would need you to tell it the type of what’s in the array and how many elements there are, and both the format string and the list of arguments would quickly get confusing.

    2. d

    3. d

  • Why do we need pointers

There is no such thing as C++ pointers. C++ is just a brand name. There are pointers. They always exist regardless of whether you’re using C++ or not. C++ grudgingly(勉强) exposes them to you; some high-level languages hide them from you. But they are always there, covertly or overtly.

Pointers Are Just Numbers.

In addition to being just number, you can also think of a pointer as being the address, or the label, of a specific byte in computer memory.

Since the pointers are the memory locations, why can’t we just remember the addresses of all the data we need, directly?

Well – honestly – until the 1980s, that is actually the way we all used to write code. When you only have 256 bytes of memory available, that’s not a lot of memory to keep track of. So we didn’t need pointers so much. You just had to remember the address of where you put evernthing, and put it there ***directly***.

But as memory got bigger, and programs got more complex, we needed some way to abstract that complexity. So now we prefer to store data ***indirectly***, using indrect addressing.

Nowadays, your cell phone has several hundred billion bytes lay around. So, code uses pointers, and pointers to pointers, and pointers to pointers to variables, and pointers to pointers to arrays of functions, and on and on like that, to keep all those code responsibilities clear.

Computers have always been very good at addressing bytes indirectly.

The assembly language of all modern CPUs lets you access data indirectly.

So, to really grok pointers, I suggest that you ignore C++ and other high level languages, and start doing a little programming in assembly language.

I know that learning assembly sounds like a huge detour, but I promise that the time you spend won’t be wasted.

Assembly programming is a pointer party, all day long.

Assembly programming is not safe, per se. There are no adults around anymore, to keep you from jabbing your own eye out with a pointer. C++ puts pointers on a high cabinet and says, clam down children, I’s the grown-up here and I will manage all the details of your pointers for you.

But assemblyy language is fast and fun as hell. When you feel the need… the need for speed… you’ll want to start manipulating pointers directly from assembly language.

  • From Wikipedia

From wikipedia, a pointer in computer science is an object that stores a memory address. This can be that of another located in computer memory, or in some cases, that of memory-mapped computer hardware.

A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer.

  1. History

    In 1955, Soviet computer scientist Kateryna Yushchenko invented the Address programming language that made possible indirect addressing and addresses of the highest rank - analogous to pointers. This language was widely used on the Soviet Union computers. However, it was unknown outside the Soviet Union and usually Harold Lawson is credited with the invention, in 1964, of the pointer.

  2. A Pointer is a kind of reference

    reference :

    In computer science, a reference is a value that enables a program to indirectly access a particular datum, such as a variable’s value or a record, in the computer’s memory or in some other storage device. The reference is said to refer to the datum, and accessing the datum is called dereferencing the reference.

    datum :

    Datum is, from its Latin origin, a singular form of “data”. From “data” in wikipedia, data are characteristics or information ,usually numberical, that are collected through observation. In a more technical sense, data is a set of values of qualitative or quantitative variables about one or more persons or objects, while a datum (singular of data) is a single value of a single variable.

    A data primitive is any datum that can be read from or written to computer memory using one memory access(for instance, both a byte and a word are primitives).

    A data aggregate is a group of primitives that are logically contiguouse in memory and that are viewed collectively as one datum. When an aggregate is entirely composed of the same type of primitive, the aggregate may be called an array.

    A byte is the smallest primitive; each memory address specifies a different byte. The memory address of the initial byte of a datum is considered the memory address (or base memory address) of the entire datum.

  • Reference

  1. cplusplus.com
  2. Everything you need to know about pointers in C
  3. How do I learn pointers in C/C++?
  4. How can I understand C++ pointers inside and out? Even after 3 semesters of C++ programming (including data structures), I still don’t fully understand how pointers work.

这篇关于理解Pointers In C++:第一重的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/860988

相关文章

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

【生成模型系列(初级)】嵌入(Embedding)方程——自然语言处理的数学灵魂【通俗理解】

【通俗理解】嵌入(Embedding)方程——自然语言处理的数学灵魂 关键词提炼 #嵌入方程 #自然语言处理 #词向量 #机器学习 #神经网络 #向量空间模型 #Siri #Google翻译 #AlexNet 第一节:嵌入方程的类比与核心概念【尽可能通俗】 嵌入方程可以被看作是自然语言处理中的“翻译机”,它将文本中的单词或短语转换成计算机能够理解的数学形式,即向量。 正如翻译机将一种语言

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

【C++高阶】C++类型转换全攻略:深入理解并高效应用

📝个人主页🌹:Eternity._ ⏩收录专栏⏪:C++ “ 登神长阶 ” 🤡往期回顾🤡:C++ 智能指针 🌹🌹期待您的关注 🌹🌹 ❀C++的类型转换 📒1. C语言中的类型转换📚2. C++强制类型转换⛰️static_cast🌞reinterpret_cast⭐const_cast🍁dynamic_cast 📜3. C++强制类型转换的原因📝

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现