指针的话题

指针与数组


 /*
     * 指针与数组
     * */
    int scores[]={65,61,26,72,83,90,100};
//    方法1
    //int *p=&scores[0];
//    方法2
    int *p=scores;
    for (int i = 0; i < sizeof(scores)/ sizeof(int); ++i) {
        //printf("%d\t\t",scores[i]);
        //printf("%d\t\t",p[i]);
        //printf("%d\t\t",*(p+i));
        //printf("%d\t\t",*(scores+i));
        //printf("%d\t\t",*(i+p));
        //printf("%d\t\t",*(i+scores));
        //printf("%d\t\t",i[scores]);
        printf("%d\t\t",i[p]);
    }
****************************************************函数******************************************************************
#include <stdio.h>
// 方法1
/*void handle1D(int marks[],int index){
    for (int i = 0; i <index ; i++) {
        printf("%d\t\t",marks[i]);
    }
}*/
//方法2
void handle1D(int *marks,int index){
    for (int i = 0; i <index ; i++) {
        printf("%d\t\t",marks[i]);
    }
}
int main() {
    /*
     * 指针与函数
     * */
    int scores[]={65,61,26,72,83,90,100};
    //方法1
//    handle1D(scores, sizeof(scores)/ sizeof(int));
//  方法2
    //handle1D(&scores[0], sizeof(scores)/ sizeof(int));
    //这个大部分编译器是不合法的   但是Clion 编译器可以出结果
    handle1D(&scores, sizeof(scores)/ sizeof(int));
    getchar();
}

指针与字符串

#include <stdio.h>

int main() {

    //char motto[]="nothing is equal to knowledge";
    char *motto="nothing is equal to knowledge";
    //输出 方法1
    printf("%s\t\n",motto);
    //输出方法2

    for (int i = 0; i <*(motto+i)!='\0' ; ++i) {
       // putchar(motto[i]);
        printf("%c",*(motto+i));
    }
    putchar(10);

    //打印下标为4的元素值
   // printf("%c\t\n",motto[4]);
    getchar();
}
****************************************函数***********************************************
#include <stdio.h>
/*
void handleString(char maxim[]){
    //方法1
    puts(maxim);
    //方法2
    for (int i = 0; maxim[i]!='\0' ; ++i) {
        putchar(maxim[i]);
    }
    //方法3
    for (int i = 0; *(maxim+i)!='\0' ; ++i) {
        putchar(*(maxim+i));
    }
}
*/


void handleString(char *maxim){
    //方法1
    puts(maxim);
    //方法2
    for (int i = 0; maxim[i]!='\0' ; ++i) {
        putchar(maxim[i]);
    }
    putchar(10);//换行
    //方法3
    for (int i = 0; *(maxim+i)!='\0' ; ++i) {
        putchar(*(maxim+i));
    }

}

int main() {
    char *motto="nothing is equal to knowledge";

    handleString(motto);
  //  handleString(&motto[0]);
  //这种方式是错误的
  /*
   *warning: passing argument 1 of 'handleString' from incompatible pointer type [-Wincompatible-pointer-types]
     handleString(&motto);

     expected 'char *' but argument is of type 'char **'
 void handleString(char *maxim){
      ^~~~~~~~~~~~
   * */
 //   handleString(&motto);

    getchar();
}

猜你喜欢

转载自www.cnblogs.com/wanson/p/10015285.html