理解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

相关文章

一文带你理解Python中import机制与importlib的妙用

《一文带你理解Python中import机制与importlib的妙用》在Python编程的世界里,import语句是开发者最常用的工具之一,它就像一把钥匙,打开了通往各种功能和库的大门,下面就跟随小... 目录一、python import机制概述1.1 import语句的基本用法1.2 模块缓存机制1.

深入理解C语言的void*

《深入理解C语言的void*》本文主要介绍了C语言的void*,包括它的任意性、编译器对void*的类型检查以及需要显式类型转换的规则,具有一定的参考价值,感兴趣的可以了解一下... 目录一、void* 的类型任意性二、编译器对 void* 的类型检查三、需要显式类型转换占用的字节四、总结一、void* 的

C++中实现调试日志输出

《C++中实现调试日志输出》在C++编程中,调试日志对于定位问题和优化代码至关重要,本文将介绍几种常用的调试日志输出方法,并教你如何在日志中添加时间戳,希望对大家有所帮助... 目录1. 使用 #ifdef _DEBUG 宏2. 加入时间戳:精确到毫秒3.Windows 和 MFC 中的调试日志方法MFC

深入理解Redis大key的危害及解决方案

《深入理解Redis大key的危害及解决方案》本文主要介绍了深入理解Redis大key的危害及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一、背景二、什么是大key三、大key评价标准四、大key 产生的原因与场景五、大key影响与危

深入理解C++ 空类大小

《深入理解C++空类大小》本文主要介绍了C++空类大小,规定空类大小为1字节,主要是为了保证对象的唯一性和可区分性,满足数组元素地址连续的要求,下面就来了解一下... 目录1. 保证对象的唯一性和可区分性2. 满足数组元素地址连续的要求3. 与C++的对象模型和内存管理机制相适配查看类对象内存在C++中,规

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

C++11的函数包装器std::function使用示例

《C++11的函数包装器std::function使用示例》C++11引入的std::function是最常用的函数包装器,它可以存储任何可调用对象并提供统一的调用接口,以下是关于函数包装器的详细讲解... 目录一、std::function 的基本用法1. 基本语法二、如何使用 std::function

认识、理解、分类——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 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数