版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/simonyucsdy/article/details/82991478
当一个数组名作为函数参数时,数组名的值就是指向数组第一个元素的指针,所以此时传递给函数的是一个地址。
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void func(char str[100]);
int main()
{
char str[] = "hello";
char *p = str;
int n = 10;
cout << "0: " << strlen(str) << endl;; //此处的str指存储在数组中的字符串
cout << "1: " << sizeof(str) << endl;; //此处的str指数组
cout << "2: " << sizeof(p) << "\n"; //此处的p是指针
cout << "3: " << sizeof(n) << '\n'; //此处的n是int整型数据
cout << endl;
char array[100] = {};
func(array);
return 0;
}
void func(char str[100])
{
cout << "4: " << sizeof(str) << '\n'; //此处的str是地址
char array[100] = {0};
cout << "5: " << sizeof(array) << '\n'; //此处的array是数组
void *p = malloc(100);
cout << "6: " << sizeof(p) << '\n'; //此处的p是指针
}
运行结果:
#include <iostream>
using namespace std;
int main()
{
int a[10] = {123, 456};
int *p;
cout << "1: " << *a << "\n"; //此处对a数组名解引用时,a代表首个元素的地址
cout << "2: " << *(a+1) << "\n"; //此处对a数组名进行加减运算时,a代表元素地址
cout << "3: " << *p << "\n"; //此处的p是一个声明但未初始化的指针
cout << "4: " << sizeof(a) << "\n"; //此处的a是数组名
cout << "5: " << sizeof(p) << "\n"; //此处的p是指针
return 0;
}
运行结果: