C++ pass value and pass address

#include<stdio.h>
struct Object 
{
    int id;
    char name[256];
};

//传值方式
void Text1(Object a)
{
    printf("id: %d,name: %s", a.id, a.name);
}

//传地址方式
void Text2(Object* a)
{
    printf("id: %d,name: %s", a->id, a->name);
}

int main()
{
    Object obj = { 123, "zhangsan" };
    Text1(obj);
    Text2(&obj);
    return 0;
}

1. Value passing method

 函数的形参是传入的实参的一份拷贝,形参是函数的局部变量,只在函数内部有效。
 在函数Text1被调用时,有两个Object对象,其中一个叫obj,定义在main函数里,另一个叫a,是函数Test1里的局部变量。
 在传值调用时,讲obj的值赋给了变量a.相当于:
 Object a = obj;
 因此说,对象a是obj的一个拷贝,下面分析这一部操作的资源消耗:
 (1)从内存资源消耗上看(空间角度),对象a耗费260个字节的内存。
 (2)从CPU资源的耗费上看(时间角度),从对象obj到对象a需要复制260个字节。

2. Address transmission method

  在函数Text2被调用时,传入一个对象obj的地址,既有一个Object*指针来表示对象obj的地址
  Object *p = &obj;
  下面分析这一部操作的资源消耗:
  (1)从内存资源消耗上看(空间角度),指针p占据4个字节,所有的指针其实只是一个整数(表示内存地址)
  (2)从CPU资源的耗费上看(时间角度),不需要复制数据,只需传递一个整数地址。

Through comparison, it is found that the performance of the address-passing method is far superior to that of the value-passing method, and it uses less resources to accomplish the same thing. In terms of memory, the address transfer method uses less memory, and in terms of CPU consumption, the address transfer method consumes very few CPU operations.
So in C/C++, when the size of an object is large (structure, array), always use the address-by-address method to pass parameters



Why does the pointer variable occupy 4 (8) bytes?

. The bit of cpu refers to the amount of data that can be processed at one time, 1 byte = 8 bits, a 32-bit processor can process 4 bytes of data at a time, and so on. 32-bit CPU design for 32-bit operating system. 64-bit CPU design for 64-bit operating system. The operating system is just a platform between hardware and application software. Our CPU has changed from the original 8-bit, 16-bit, to the current 32-bit and 64-bit.

# include<stdio.h>
int main(void)
{
int i = 373;
double j = 4.5;
char ch = ‘A’;

int * p = &i;
double * q = &j;
char * r = &ch;

printf(“%d %d %d\n”,sizeof(p), sizeof(q), sizeof(r));
return 0;
}

运行结果是 4 4 4

Different from ordinary variables, pointers store the address of the variable. The address length is the same under the same architecture (the maximum addressable memory space of the cpu), so the lengths of different types of pointers are the same. The output 4 4 4 indicates that the pointer The length is 4 bytes, and the address range that can be recorded is 0x00000000~0xFFFFFFFF, and this range is the value of the pointer variable. For example, a char of 1 byte can exist at 0x0 or at 0xFFFFFFFF, and it has nothing to do with char occupying 1 byte or 100 bytes. *The range of the pointer is only related to the machine word and the system. For example, your 32-bit system, the pointer length It is 4, and it is 8 under the 64-bit operating system.

Guess you like

Origin blog.csdn.net/yulong_abc/article/details/81676696