內容選單標籤

2021年7月30日 星期五

C操作

 struct 結構
----------------------------------------------------------
#include<stdio.h>
//#include<stdlib.h>
int main(void){
struct score{
char sid[4];
int math;
}John={"s01",80},Tom={"s02",96};
printf("0: name chinese math\n");
printf("1: John %s %d\n",John.sid,John.math);
printf("2: Tom %s %d\n",Tom.sid,Tom.math);
return 0;
}
0: name chinese math
1: John s01     80
2: Tom  s02     96



結構指標
+++++++++++++++
//#include<stdlib.h>
#include<stdio.h>
void main(){
struct score{
char sid;
int math;
struct score *next;
};
typedef struct score stu;
stu John,Tom,*begin;
John.sid='J';
John.math=80;
John.next=NULL;

Tom.sid='T';
Tom.math=90;
Tom.next=NULL;
John.next=&Tom;
begin=&John;
printf("sid    math\n");
while(begin!=NULL){
printf("%c    %d    \n",begin->sid,begin->math);
begin=begin->next
}
}
sid    math
J    80
T    90





陣列模擬結構指標  saved as *.cpp
+++++++++++++++
//#include<stdlib.h>
//#include<stddef.h>
#include<stdio.h>
int main(void){
int stu[]={65,80,3,66,75,999};
int begin=0;
printf("sid    math\n");
while(begin!=999){
printf("%c    %d\n",stu[begin],stu[begin+1]);
begin=stu[begin+2]; 
}
return 0;
}

sid    math
A    80
B    75


----------------------------------------------------------





全域、區域變數
+++++++++++++++
#include<stdio.h>
//全域
int A=80;

void fun(){
        //區域2
int A=50;
printf("區域2前%d",A);
A=A+10;
printf("區域2後%d\n",A);

int main(void){
printf("全域前=%d",A);
A=A+3;
printf("全域後%d\n",A);
//區域 
int A=0;
printf("區域前=%d",A);
for (int i=0;i<5;i++){
A=A+i;
printf("區域中%d",A);
printf(";");
}
A=A+3;
printf("區域後%d\n",A);
fun();
return 0;
}

全域前=80全域後83
區域前=0區域中0;區域中1;區域中3;區域中6;區域中10;區域後13
區域2前50區域2後60





交換2數 傳值 傳址
----------------------------------------------------------
#include<stdio.h>

void swap1(int x,int y){
int tmp;
tmp=x;
x=y;
y=tmp;


void swap2(int *x,int *y){
int tmp;
tmp=*x;
*x=*y;
*y=tmp;
}


int main(void){
int x=10;
int y=0;
printf("初值 x=%d y=%d\n",x,y);
swap1(x,y);
printf("傳值 x=%d y=%d\n",x,y);
swap2(&x,&y);
printf("傳址 x=%d y=%d\n",x,y);
return 0;
}

初值 x=10 y=0
傳值 x=10 y=0
傳址 x=0 y=10
----------------------------------------------------------


----------------------------------------------------------

----------------------------------------------------------


----------------------------------------------------------


----------------------------------------------------------

----------------------------------------------------------



----------------------------------------------------------


----------------------------------------------------------

----------------------------------------------------------

沒有留言:

張貼留言