zoukankan      html  css  js  c++  java
  • 数组与指针实例

    1.#include <stdio.h>

    int main()
    {
        int a[5] = {1, 2, 3, 4, 5};
        int* p1 = (int*)(&a + 1);
        int* p2 = (int*)((int)a + 1);
        int* p3 = (int*)(a + 1);
        
        printf("%d, %d, %d ", p1[-1], p2[0], p3[1]);
        
        return 0;
    }
    // A. 数组下标不能是负数,程序无法运行
    // B. p1[-1]将输出随机数,p2[0]输出2, p3[1]输出3
    // C. p1[-1]将输出乱码, p2[0]和p3[1]输出2

    2.#include <stdio.h>
    #include <malloc.h>

    int main()
    {
        char s1[] = {'H', 'e', 'l', 'l', 'o'};
        int i = 0;
        char s2[] = {'W', 'o', 'r', 'l', 'd'};
        char* p0 = s1;
        char* p1 = &s1[3];
        char* p2 = s2;
        int* p = &i;
        
        printf("%d ", p0 - p1);
        //printf("%d ", p0 + p2);
        printf("%d ", p0 - p2);
        //printf("%d ", p0 - p);
        //printf("%d ", p0 * p2);
        //printf("%d ", p0 / p2);
        
        return 0;
    }

    3.#include <stdio.h>
    #include <malloc.h>

    #define DIM(a) (sizeof(a) / sizeof(*a))

    int main()
    {
        char s[] = {'H', 'e', 'l', 'l', 'o'};
        char* pBegin = s;
        char* pEnd = s + DIM(s);//指向字符数组的后一个元素,这里并未访问,所以没有越界。
        char* p = NULL;
        
        for(p=pBegin; p<pEnd; p++)
        {
            printf("%c", *p);
        }
        
        printf(" ");
        
        return 0;
    }
    4.#include <stdio.h>
    #include <time.h>

    int main()
    {
        clock_t start;
        clock_t end;
        int a[10000];
        int b[10000];
        int* pEnd = &a[10000];
        int* pa = NULL;
        int* pb = NULL;
        int i = 0;
        int k = 0;
        
        start = clock();
        
        for(k=0; k<10000; k++)
        {
            for(i=0; i<10000; i++)
            {
                b[i] = a[i];
            }
        }
        
        end = clock();
        
        printf("Index Timing: %d ", end - start);
        
        start = clock();
        
        for(k=0; k<10000; k++)
        {
            for(pa=a, pb=b; pa<pEnd;)
            {
                *pb++ = *pa++;
            }
        }
        
        end = clock();
        
        printf("Pointer Timing: %d ", end - start);
        
        return 0;
    }

  • 相关阅读:
    响应式布局,流式布局与固定布局
    垃圾回收机制
    形象讲解时间复杂度
    数据结构和算法简介
    数据结构之栈和队列
    十、str的索引、切片和str常用的操作方法(重点)
    九、基础数类型总览和str、int、bool之间的相互转化
    八、编码的初识和进阶
    七、格式化输出和运算符
    六、while循环
  • 原文地址:https://www.cnblogs.com/wxb20/p/6150483.html
Copyright © 2011-2022 走看看