zoukankan      html  css  js  c++  java
  • c程序设计语言 by K&R(二)指针与数组

    指针与数组

    1. c语言只有值传递,没有引用传递

    • 可通过指针交换
    #include <stdio.h>
    #include <stdlib.h>
    void swap(int* a, int* b){
    	int tmp = *b;
    	*b = *a;
    	*a = tmp;
    }
    int main(void) {
    	int a = 2;
    	int b = 3;
    	swap(&a, &b);
    	printf("%d %d\n", a, b);
    	return 0;
    }
    
    • 但以下代码在c++环境下才能运行
    void swap(int& a, int& b){
    	int tmp = b;
    	b = a;
    	a = tmp;
    }
    int main(void) {
    	int a = 2;
    	int b = 3;
    	swap(a, b);
    	printf("%d %d\n", a, b);
    	return 0;
    
    

    2. (*ip)++

    如果实现对ip所指对象进行自增,(*ip)++ 中的括号是必须的。否则改表达式对ip进行+1运算,而非对ip所指对象进行+1运算。因为类似于* 、++这样的一元运算符遵循从右至左的结合顺序。

    3. char s[]和 char* s是等价的

    s是字符数组的起始地址

    4. C语言不进行数组越界检查

    arr[-1],arr[-2]表示arr[0]之前的两个元素

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
    	int c[2] = {0,0};
    	printf("%d %d\n", c[-1], c[-2]);
    	return 0;
    }
    

    输出:

    32767 -502976128
    

    5. void*是一种特殊的指针类型

    可以用来存放任意对象的地址。一个void指针存放着一个地址,这一点和其他指针类似。不同的是,我们对它到底储存的是什么对象的地址并不了解。

    6. strcpy的实现

    • 通过数组实现
    void strcpy_a(char* s, char* t){
        int i = 0;
        while((s[i] = t[i]) != '\0')
            i ++;
    }
    
    
    • 通过指针实现
    void strcpy_p(char* s, char* t){
      while(*s++ = *t++);
    }
    

    7. strcmp的实现

    • 通过指针实现
    int strcmp_p(char* s, char* t){
        for(;*s == *t; s++, t++){
            if(*s == '\0') return 0;
        }
        return *s - *t;
    }
    
    
    
    • 通过数组实现
    int strcmp_a(char* s, char* t){
        int i;
        for(i = 0; s[i] == t[i]; i++)
            if(s[i] == '\0') return 0;
        return s[i] - t[i];
    }
    

    8.命令行参数

    main(int argc, char* argv){}

    argc表示程序运行时命令行中参数的数目;argv指向字符串数组的指针,每个字符串对应一个参数

    • 实现say程序:
    #include<stdio.h>
    int main(int argc, char* argv[]){
            printf("%d\n", argc);
            for(int i = 0; i < argc; i++){
                    printf("%s\n",argv[i]);
            }
            return 0;
    }
    
    • 命令行运行:
      gcc say.c -o say
      ./say hello world

    • 输出:

  • 相关阅读:
    [后缀数组] Luogu P5028 Annihilate
    [后缀数组] Luogu P3809 后缀排序
    [差分][线段树] Luogu P4243 等差数列
    [线段树] Luogu P4314 COU监控
    [二分][dp凸优化] Luogu P4383 林克卡特树lct
    [树上差分][dfs] Luogu P4652 One-Way Streets
    [dfs][思维] Luogu P3208 矩阵
    [dfs][二进制状压] Luogu P4906 小奔关闹钟
    [容斥] Luogu P5339 唱、跳、rap和篮球
    [dfs][模拟网络流] Luogu P4189 星际旅行
  • 原文地址:https://www.cnblogs.com/qiangz/p/15783031.html
Copyright © 2011-2022 走看看