2.21指针法和数组法操作字符串

【注:本程序验证是使用vs2013版】

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)

int main(void){
    char buf[] = "asdwqfqwerwefq";

    //1.访问字符串  ---数组方式
    for (int i = 0; i < strlen(buf); i++){
        printf("%c", buf[i]);
    }
    printf("\n");
  
//2.访问字符串 -- - 纯指针方式 char *b = buf; for (int i = 0; i < strlen(buf); i++){ printf("%c", *(b + i)); //可以用这种方式,编译器本身是通过这种方式跳转的 } printf("\n");
  
//3.访问字符串 ---不伦不类方式 char *a = buf;//数组名字,数组首元素地址 for (int i = 0; i < strlen(buf); i++){ printf("%c", a[i]); } printf("\n");
  
//4.访问字符串 ---不伦不类方式 for (int i = 0; i < strlen(buf); i++){ printf("%c", *(buf + i)); } printf("\n");
  
/* 思考:buf和p完全等价吗? buf:数组名也是指针,数组首元素地址,但是,【它是一个只读常量】; 因为在栈中定义好的首地址和长度,后期有利于系统回收 理解 *(buf + 1); //ok 这里将buf当做一个固定值来操作的 *(buf++); //err 只有变量才可以这样操作 */ printf("\n"); system("pause"); return 0; }

猜你喜欢

转载自www.cnblogs.com/wlstm/p/11100591.html
今日推荐