1. 程式人生 > >c語言知識

c語言知識

指標、指標與陣列、指標與字元陣列及指標與函式

宣告:int *p = NULL;p為地址*類似鑰匙*p就是該地址所指向的值。

#include <stdio.h>

#include <stdlib.h>

int main(){

int a=10;

int *p = NULL;

p=&a;

printf("%d",*p)//*p的值就為a的值,即10

system("pause");

retrun 0;

}

#include <stdio.h>

#include <stdlib.h>

int main(){

int b[] = {1,2,3,4,5,6};

int *p = NULL;

p=&a;//此時p的地址為&a[0]

printf("%x",*p)//*pa[0]的值

system("pause");

retrun 0;

}

#include <stdio.h>

#include <stdlib.h>

int main(){

int b[] = {1,2,3,4,5,6};

int *p = NULL;

p=&a;

printf("%x",*(p+1))//*(p+1)a[1]的值

system("pause");

retrun 0;

}

#include <stdio.h>

#include <stdlib.h>

int main(){

int a[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

int *p = NULL;

p = a[0][0];

for (int i = 0; i<3; i++) {

for (int j = 0; j<4; j++) {

printf("&a[%d][%d] = %x\n",i,j,&a[i][j]);//輸出a[i][j]的地址

printf(“a[%d][%d]= %d\n”,i,j,a[i][j]);//輸出a[i][j]的值

printf("%d\n",*(p+i*4+j));//p輸出a[i][j]的地址

}

}

system("pause");

retrun 0;

}

#include<stdio.h>

#include<stdlib.h>

int main(){

int i,j;

int a[2][3]={{1,2,3},{4,5,6}};

int (*p)[3] = NULL;

p=a;

for(i = 0;i<2;i++){

for(j = 0;j<3;j++){

printf("%d\n",*(*(p+i)+j));

}

}

system("pause");//通過指標來確定陣列元素的位置

return 0;

}

#include <stdio.h>

#include <stdlib.h>

void swap(int *p1, int *p2) {

int p;

p=*p1;

*p1=*p2;

*p2=p;

}

int main(){

int a=10;

int b=20;

swap(&a,&b);

printf("a=%d,b=%d",a,b);//a,b交換位置

system("pause");

retrun 0;

}

#include <stdio.h>

#include <stdlib.h>

int main(){

char *ch ="1234";

printf("%s\n",ch);//ch可以直接輸出字串”1234”,與其他陣列不同的地方

return 0;

system("pause");

}

#include <stdio.h>

#include <stdlib.h>

int max(int a,int b){

    if(a>b) {

        return a;

    }

    else{

        return b;

    }

}

int main(){

int (*p)(int,int);

    p = max;

  int c = p(10,20);

printf("c = %d\n",c);//輸出較小的數

    return 0;

}