本文目錄一覽:
- 1、用c語言結構體編寫
- 2、c語言中結構體怎麼寫
- 3、C語言結構體編程
用c語言結構體編寫
//很明顯這是結構體定義
struct studentNode{
char name[30];
char sno[30];
};
//比較字元數組的函數,對於結構體中的字元數組,直接用串比較可能會錯誤處理一些特殊字元。
bool compare(const char* str1,const char* str2){
for(int i = 0 ; i 30 ; i++){
if(str1[i] != str2[i]){
if(str1[i] str2[i]){
return true;
}else{
return false;
}
}
}
return true;
}
//排序函數,傳入結構體數組指針,長度,第三個參數是是否為降序
void sortWithSno(studentNode* stu, int len , bool isdesc){
studentNode temp;
for(int i = 0 ; i len ; i++){
for(int j = 0 ; j len ; j++){
if(isdesc){
if(compare((*(stu+i)-sno) , (*(stu+j)-sno))){
temp = *(stu+j);
*(stu+j) = *(stu+i);
*(stu+i) = temp;
}
}else{
if(!compare((*(stu+i)-sno) , (*(stu+j)-sno))){
temp = *(stu+j);
*(stu+j) = *(stu+i);
*(stu+i) = temp;
}
}
}
}
}
//同上,可以將兩個函數合併,中間再加一層結構體成員的枚舉選擇器
void sortWithName(studentNode* stu, int len , bool isdesc){
studentNode temp;
for(int i = 0 ; i len ; i++){
for(int j = 0 ; j len ; j++){
if(isdesc){
if(compare((*(stu+i)-name) , (*(stu+j)-name))){
temp = *(stu+j);
*(stu+j) = *(stu+i);
*(stu+i) = temp;
}
}else{
if(!compare((*(stu+i)-name) , (*(stu+j)-name))){
temp = *(stu+j);
*(stu+j) = *(stu+i);
*(stu+i) = temp;
}
}
}
}
}
//很明顯這是個列印函數
void print(studentNode stu[],int len){
for(int i = 0 ; i len ; i++){
printf(“%d: name: %s sno:%s\n”,i,stu[i].name,stu[i].sno);
}
}
注意這程序中使用了結構體直接複製,老TC應該會掛掉,用最新的GCC能編譯。
c語言中結構體怎麼寫
以struct打頭,後面可以跟結構體名稱,然後大括弧中寫出結構體組成,比如:
struct Student { int number; float score[5]; };
其中Student就是結構體名稱,這個名稱可以當作自定義的數據類型來使用
Student a[10];
C語言結構體編程
#includestdio.h
#includestdlib.h
typedef struct
{
char num[10];
int s;
}strec;
int N;
int fun(strec*a,strec*b)
{
int i,j=0;
strec max;
for(i=0;iN;i++)
{
printf(“輸入姓名:”);
scanf(“%s”,a[i].num);
printf(“輸入分數:”);
scanf(“%d”,a[i].s);
}
max=a[0];
for(i=0;iN;i++)
if(max.sa[i].s)
max=a[i];
for(i=0;iN;i++)
if(max.s==a[i].s)
{ b[j]=a[i];
j++;
}
for(i=0;ij;i++)
{
printf(“%s “,b[i].num);
printf(“%d”,b[i].s);
printf(“\n”);
}
return j;
}
void main()
{
strec *a,*b;
int n;
printf(“input N:”);
scanf(“%d”,N);
a=(strec*)malloc(N*sizeof(strec));
b=(strec*)malloc(N*sizeof(strec));
n=fun(a,b);
printf(“最高分有%d人\n”,n);
}
採納時多給點分!橋這麼多代碼不容易啊!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/293215.html