C++ 教程 在线

2637cpp-pointer-arithmetic

指针指向数组中某一元素时要用 &

#include <iostream>
using namespace std;
int main()
{
    int  var[5] = {1,2,3,4,5};   // 实际变量的声明
    int  *ip;        
    // 指针变量的声明  
    int  *ip_1;
    //ip = &var;
    //指针指向数组的时候不用 “&”取址符
    //ip = &var[2]
    //指针指向数组某一元素时要用 “&”取址符
    ip = var; 
    // 在指针变量中存储 var 的地址
    ip_1 = &var[2];
    // 在指针变量中存储 var[2] 的地址
    cout << "Value of var variable: ";
    cout << var << endl;
    // 输出在指针变量中存储的地址
    cout << "Address stored in ip variable: ";
    cout << ip << endl;
    // 访问指针中地址的值    
    cout << "Value of *ip variable: ";
    *ip = 30;
    cout << *ip << endl;
    cout << "\t" << var << endl;
    // 打印指针指向数组的某一元素的值  
    cout << "Value of *ip_1 variable:";
    cout << *ip_1 << endl;
    // system("pause"); 
    return 0;
}

2636cpp-pointer-arithmetic

指针指向数组的时候,不可以加 &:

#include <iostream>
using namespace std;
int main()
{
    int  var[5] = {1,2,3,4,5};   // 实际变量的声明
    int  *ip;        // 指针变量的声明
    ip = &var;       // 在指针变量中存储 var 的地址
    cout << "Value of var variable: ";
    cout << var << endl;
    // 输出在指针变量中存储的地址
    cout << "Address stored in ip variable: ";
    cout << ip << endl;
    // 访问指针中地址的值
    cout << "Value of *ip variable: ";
    *ip = 30;
    cout << *ip << endl;
    cout << var << endl;
    system("pause");
    return 0;
}

2635cpp-return-arrays-from-function

srand以一个时间点为参数播种,当执行的随机数少的时候,时间没有变化,产生的随机数是一样的,下面这例子,输入的很多,前面几十个随机数都是一样的,当时间增加一个单位之后生成的随机数就不一样了,会递增,所以 srand 函数要放在 rand 循环的外面避免每次循环产生的随机数一样。

# include<stdlib.h>
# include<iostream>
# include<time.h>
int main(){
//    srand((unsigned)time(NULL));    
for (int i = 0; i < 100000; ++i) {
       srand((unsigned)time(NULL));       
       int a=rand();       
       std::cout<<a<<std::endl;   
   }
}

2634cpp-return-arrays-from-function

『返回指针的函数』和『指向函数的指针』非常相似,使用时特别注意区分。

返回指针的函数定义:char * upper(char *str)

指向函数的指针:char (*fun)(int int)

返回指针的函数:

char * upper(char *str)
{
    char *dest = str;
    while(*str != NULL)
    {
        if(*str >= 'a' && *str <= 'z')
        {
            *str -= 'a' - 'A';
        }
        str++;
    }
    return dest;
}

指向函数的指针:

int add(int a,int b)
{
    return a+b;
}
int min()
{
    int (*fun)() = add;
    int result = (*fun)(1,2);
    char hello[] = "Hello";
    char *dest = upper(heLLo);
}

int result = (*fun)(1,2); 是指向 add 函数的函数,执行结果 result=3

char *dest = upper(heLLo); 将 hello 字符串中的小写字母全部转换为大写字母。

2633cpp-passing-arrays-to-functions

@YoungWilliam

arr 是一个指针,即为地址,指针占几个字节跟语言无关,而是跟系统的寻址能力有关。

例如:以前是 16 位地址,指针即为 2 个字节,现在一般是 32 位系统,所以是 4 个字节,以后 64 位,则就占 8 个字节。