Question: 求助，c语言作业，不太会

一堆问题。基本的问题有三：1，int loadrecord（） 函数申明与函数原型 参数数量都不同。2，打印出版时间的地方，是要打印年月日的。 参数却少了年月日。3，有个函数定义的地方，括号混乱。 是哪儿抄的作业。。。抄都抄不整齐。

int loadrecord(struct library book[],int n);声明的时候是两个形参。int loadrecord(struct library book[]){}  函数实现时只有一个参数。排版 修改如下，供参考： #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> #include"windows.h" #define M 50   struct date {      int year;      int month;      int day; };  struct library {     int  book_num;     char book_name[40];     char author_name[10];     float book_price;     char publisher[40];     struct date publish_time;     char book_state[2];     char reader_name[10];     int reader_num; };  int input(struct library book[]); int add(struct library book[],int n); void list(struct library book[],int n); void search_num(struct library book[],int n); void search_name(struct library book[],int n); int Delete(struct library book[],int n); void sort(struct library book[],int n); void count(struct library book[],int n); void unborrow(struct library book[],int n); void search_publisher(struct library book[],int n); void saverecord(struct library book[],int n); int loadrecord(struct library book[]);       //,int n); int menu();  void main() {     struct library b[M];     int    length;     while(1)     {       switch(menu())     {              case 1:length=input(b);                     if(length==-1)break;                     else                       saverecord(b,length);                     break;              case 2:length=loadrecord(b);                     length=add(b,length);                     saverecord(b,length);                     break;              case 3:length=loadrecord(b);                     list(b,length);                     break;              case 4:length=loadrecord(b);                     search_num(b,length);                     break;              case 5:length=loadrecord(b);                     search_name(b,length);                     break;              case 6:length=loadrecord(b);                     length=Delete(b,length);                     saverecord(b,length);                     break;              case 7:length=loadrecord(b);                     sort(b,length);                     saverecord(b,length);                     list(b,length);                     break;              case 8:length=loadrecord(b);                     count(b,length);                     saverecord(b,length);                     break;              case 9:length=loadrecord(b);                     unborrow(b,length);              case 10:length=loadrecord(b);                     search_publisher(b,length);                     break;              case 0:exit(0);     }     } } int menu() {    int c;    system("mode con:cols=400 lines=30000"); //调节控制台的宽度和高度    system("color 0b");  //调节控制台的背景和字体颜色      printf("\t\t\t\t\t-------------------------------------------------\n");    printf("\t\t\t\t\t+ 图书信息管理系统         +\n");    printf("\t\t\t\t\t-------------------------------------------------\n");    printf("\t\t\t\t\t\t\t ***************\n");    printf("\t\t\t\t\t\t\t 1. 初始化图书信息\n");                             printf("\t\t\t\t\t\t\t 2. 添加图书信息\n");                       printf("\t\t\t\t\t\t\t 3. 显示图书信息\n") ;    printf("\t\t\t\t\t\t\t 4. 按图书编号查询图书信息\n");         printf("\t\t\t\t\t\t\t 5. 按图书名称查询图书信息\n");                     printf("\t\t\t\t\t\t\t 6. 按图书名称删除图书信息\n");         printf("\t\t\t\t\t\t\t 7. 按图书名称从小到大排序图书信息\n");                       printf("\t\t\t\t\t\t\t 8. 按价格统计图书信息\n") ;    printf("\t\t\t\t\t\t\t 9. 显示未借出图书信息\n");    printf("\t\t\t\t\t\t\t 10. 修改图书信息\n");    printf("\t\t\t\t\t\t\t 11. 按出版社名称查询图书信息\n");    printf("\t\t\t\t\t\t\t 0. 退出\n") ;                                           printf("\t\t\t\t\t\t\t ***************\n");     do{        printf("\n  Enter your choice(0-10):");              if(scanf("%d",&c)!=1)        {  while(getchar()!='\n')             continue;             continue;        }     }while(c<0||c>11);     return c; } int input(struct library book[]) {     int i,n;     system("cls");     printf("\t输入图书的数量：\n");     scanf("\t\t\t\t%d",&n);     system("cls");     printf("\t开始输入记录：\n");     for(i=0;i<n;i++)     {          printf("\n\t第%d条记录的图书编号：",i+1);          scanf("\t%d",&book[i].book_num);           printf("\t第%d条记录的图书名称：",i+1);          scanf("\t%s",book[i].book_name);           printf("\t第%d条记录的图书作者姓名：",i+1);          scanf("\t%s",book[i].author_name);           printf("\t第%d条记录的图书价格：",i+1);          scanf("\t%f",&book[i].book_price);           printf("\t第%d条记录的图书出版社：",i+1);          scanf("\t%s",book[i].publisher);           printf("\t第%d条记录的图书出版时间：",i+1);          scanf("\t%d-%d=%d",&book[i].publish_time.year,                    &book[i].publish_time.month,&book[i].publish_time.day);           printf("\t第%d条记录的图书存在状态(y/n)：",i+1);          scanf("\t%s",book[i].book_state);           printf("\t第%d条记录的读者姓名：",i+1);          scanf("\t%s",book[i].reader_name);           printf("\t第%d条记录的读者学号：",i+1);          scanf("\t%d",&book[i].reader_num);     }     printf("\t******************\n");     printf("\t   已输入成功！\n");     printf("\t  press any key enter menu......\n");     printf("\t******************\n");     getchar();     getchar();     system("cls");     return n; }   int add(struct library book[],int n) {     int i,m;     system("cls");     printf("\t输入再增加的记录数：\n");     scanf("%d",&m);     printf("\t开始输入记录：\n");     for(i=n;i<n+m;i++)     {         printf("\n\t第%d条记录的图书编号：",i+1);         scanf("\t%d",&book[i].book_num);          printf("\t第%d条记录的图书名称：",i+1);         scanf("\t%s",book[i].book_name);          printf("\t第%d条记录的图书作者姓名：",i+1);         scanf("\t%s",book[i].author_name);          printf("\t第%d条记录的图书价格：",i+1);         scanf("\t%f",&book[i].book_price);          printf("\t第%d条记录的图书出版社：",i+1);         scanf("\t%s",book[i].publisher);          printf("\t第%d条记录的图书出版时间：",i+1);         scanf("\t%d-%d=%d",&book[i].publish_time.year,               &book[i].publish_time.month,&book[i].publish_time.day);          printf("\t第%d条记录的图书存在状态(y/n)：",i+1);         scanf("\t%s",book[i].book_state);          printf("\t第%d条记录的读者姓名：",i+1);         scanf("\t%s",book[i].reader_name);          printf("\t第%d条记录的读者学号：",i+1);         scanf("\t%d",&book[i].reader_num);     }     printf("\t******************\n");     printf("\t   已输入成功！\n");     printf("\t  press any key enter menu......\n");     printf("\t******************\n");     getchar();     getchar();     system("cls");     return (n+m); } void list(struct library book[],int n) {      int i;      system("cls");        printf("\t图书馆图书信息如下:\n");      printf("\t图书编号\t图书名称\t作者\t单价\t出版社\t\t出版时间\t存在状态\t读者姓名\t读者学号\n");      for(i=0;i<n;i++)      {           printf("\t%6d\t%12s\t%10s\t%4.2f\t%6s\t",book[i].book_num,book[i].book_name,                              book[i].author_name,book[i].book_price,book[i].publisher);           printf("\t%4d-%2d-%2d\t%2s\t%6s\t%8d\t\n",book[i].publish_time,book[i].book_state,                                                      book[i].reader_name,book[i].reader_num);      }       printf("\t***************************\n");      printf("\t  press any key enter menu......\n");      printf("\t***************************\n");      getchar();      getchar();      system("cls"); } void search_num(struct library book[],int n) {     int i,flag=0;     int bnum;     system("cls");     printf("\t输入查询编号：\n");     scanf("%d",&bnum);     for(i=0;i<n;i++)     {         if(book[i].book_num==bnum)             flag=1;         system("cls");         printf("\t图书馆图书信息如下:\n");         printf("\t图书编号\t图书名称\t作者\t单价\t出版社\t\t出版时间\t存在状态\t读者姓名\t读者学号\n");         printf("\t%6d\t%12s\t%10s\t%4.2f\t%6s\t",book[i].book_num,book[i].book_name,                            book[i].author_name,book[i].book_price,book[i].publisher);         printf("\t%4d-%2d-%2d\t%2s\t%6s\t%8d\t\n",book[i].publish_time,book[i].book_state,                                                    book[i].reader_name,book[i].reader_num);         printf("\t***************************\n");         printf("\t  press any key enter menu......\n");         printf("\t***************************\n");         getchar();         getchar();         system("cls");     }     if(flag==0)     {         printf("查无此书！\n");         printf("\t***************************\n");         printf("\t  press any key enter menu......\n");         printf("\t***************************\n");         getchar();         getchar();         system("cls");     } }   void search_name(struct library book[],int n) {     int i,flag=0;     char bname[10];     system("cls");     printf("\n请输入要查询的图书书名:");     scanf("%s",bname);     for(i=0;i<n;i++)     {        if(strcmp(bname,book[i].book_name)==0)        {           flag=1;           system("cls");           printf("\t此书的信息如下：\n");           printf("\t图书编号\t图书名称\t作者\t单价\t出版社\t\t出版时间\t存在状态\t读者姓名\t读者学号\n");           printf("\t%6d\t%12s\t%10s\t%4.2f\t%6s\t",book[i].book_num,book[i].book_name,                              book[i].author_name,book[i].book_price,book[i].publisher);           printf("\t%4d-%2d-%2d\t%2s\t%6s\t%8d\t\n",book[i].publish_time,                                  book[i].book_state,book[i].reader_name,book[i].reader_num);           printf("\t***************************\n");           printf("\t  press any key enter menu......\n");           printf("\t***************************\n");           getchar();           getchar();           system("cls");        }     }     if(flag==0)     {          printf("没有此书!\n");           printf("\t***************************\n");          printf("\t  press any key enter menu......\n");          printf("\t***************************\n");          getchar();          getchar();          system("cls");     } }  int Delete(struct library book[],int n) {     int i,j,flag=0;     char bname[10];     char ch='n';     system("cls");     printf("请输入要删除的图书名字\n");     scanf("%s",bname);     for(i=0;i<n;i++)     {        if(strcmp(bname,book[i].book_name)==0)        {           flag=1;           printf("\t此书的信息如下:\n");           printf("\t图书编号\t图书名称\t作者\t单价\t出版社\t\t出版时间\t存在状态\t读者姓名\t读者学号\n");           printf("\t%6d\t%12s\t%10s\t%4.2f\t%6s\t",book[i].book_num,book[i].book_name,                              book[i].author_name,book[i].book_price,book[i].publisher);           printf("\t%4d-%2d-%2d\t%2s\t%6s\t%8d\t\n",book[i].publish_time,book[i].book_state,                                                      book[i].reader_name,book[i].reader_num);                       printf("是否要删除此条信息!(y/n):");           ch=getchar();           ch=getchar();           if(ch=='y'||ch=='Y')           {              for(j=i;j<n-1;j++)                  book[j]=book[j+1];              n--;              printf("是否要删除此信息！(y/n):");           }           printf("\t***************************\n");           printf("\t  press any key enter menu......\n");           printf("\t***************************\n");           getchar();           getchar();           system("cls");        }     }     if(flag==0)     {          printf("\t  查无此书！\n");           printf("\t***************************\n");          printf("\t  press any key enter menu......\n");          printf("\t***************************\n");          getchar();          getchar();           system("cls");     }     return n; } void sort(struct library book[],int n) { } void count(struct library book[],int n) {      int i,count1=0;float p;      system("cls");      printf("请输入任意一个价格：");      scanf("%f",&p);       for(i=0;i<n;i++)      {          if(book[i].book_price>p)            count1++;      }      printf("\t图书的数量为:%d \n\n\n\n",count1);       printf("\t***************************\n");      printf("\t  press any key enter menu......\n");      printf("\t***************************\n");      getchar();      getchar();      system("cls"); }  void unborrow(struct library book[],int n) { }  void saverecord(struct library book[],int m)//初始化图书信息else {     int i;     FILE *fp;     if((fp=fopen("record.txt","w"))==NULL)     {        printf("无法录入信息!!\n");        exit(1);     }     for(i=0;i<m;i++)       fwrite(&book[i],sizeof(struct library),1,fp);     fclose(fp); } int loadrecord(struct library book[])//添加图书信息else {     int n=0;     FILE *fp;     if((fp=fopen("record.txt","r"))==NULL)     {         printf("无法录入信息!!\n");         exit(0);     }     while(fread(&book[n],sizeof(struct library),1,fp))n++;     fclose(fp);     printf("从文件中成功读出记录!!!\n");     return n; }  void search_publisher(struct library book[],int n) {     int i,flag=0;     char bpublisher[10];     system("cls");     printf("\n请输入要查询的出版社名称:");     scanf("%s",bpublisher);     for(i=0;i<n;i++)     {         if(strcmp(book[i].publisher,bpublisher)==0)         {            flag=1;            system("cls");            printf("\t此书的信息如下：\n");            printf("\t图书编号\t图书名称\t作者\t单价\t出版社\t\t出版时间\t存在状态\t读者姓名\t读者学号\n");            printf("\t%6d\t%12s\t%10s\t%4.2f\t%6s\t",book[i].book_num,book[i].book_name,                               book[i].author_name,book[i].book_price,book[i].publisher);            printf("\t%4d-%2d-%2d\t%2s\t%6s\t%8d\t\n",book[i].publish_time,book[i].book_state,                                                       book[i].reader_name,book[i].reader_num);            printf("\t***************************\n");            printf("\t  press any key enter menu......\n");            printf("\t***************************\n");            getchar();            getchar();            system("cls");         }     }     if(flag==0)     {       printf("没有此书!\n");        printf("\t***************************\n");       printf("\t  press any key enter menu......\n");       printf("\t***************************\n");       getchar();       getchar();       system("cls");     }     //}     //return n; }

C:\Users\lenovo\Desktop\wangyujie.cpp(53) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(57) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(60) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(63) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(66) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(70) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(75) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(79) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(81) : error C2660: 'loadrecord' : function does not take 1 parametersC:\Users\lenovo\Desktop\wangyujie.cpp(416) : error C2601: 'search_publisher' : local function definitions are ille这是显示错误的地方


Question: 这个程序在vc6.0上编译时会出现许多问题，但在dev上面编译时只有一个错误:	[Error] ld returned 1 exit status（makefiles.win文件里），想知道这个程序应该怎样改才能正常运行，在Dev里有时可以编译成功。

这是代码运行的部分截图：

修改完善如下，供参考： #include<stdio.h> #include<stdlib.h> #include<string.h> #include <time.h> struct Signal {     char  Name[10];    //名字     int   KB;          //开放状态     float Pos;        //地址     int   Type;       //闭锁継电器状态     struct Signal *next,*front; };  struct Signal*head=NULL; int    i_count=0;      //全局 计数  void   write(struct Signal*head); void   read(struct Signal*&head); void   creat(struct Signal *&head); void   chaxun(struct Signal*head); void   change(struct Signal* head); void   delete_xinhaoji(struct Signal*head); void   myfree(struct Signal*head); void   Change(struct Signal *head);  void   creat(struct Signal *&head) {     char answer='t';     struct Signal*p1,*p2,*pr;     if(head==NULL)     {             head=(struct Signal*)malloc(sizeof(struct Signal));             if(!head)  return;             head->next=NULL;     }     pr=head;     p2=head->next;     while(p2){pr=p2; p2=p2->next;}     while(answer!='F'&& answer!='f')     {         p1=(struct Signal*)malloc(sizeof(struct Signal));         p1->next=NULL;         printf("请输入第%d架信号机的名称：\n",i_count+1);         fflush(stdout);rewind(stdin);         scanf("%s",p1->Name);         printf("请输入第%d架信号机的开放状态：\n",i_count+1);         fflush(stdout);rewind(stdin);         scanf("%d",&p1->KB);         printf("请输入第%d架信号机的地址：\n",i_count+1);         fflush(stdout);rewind(stdin);         scanf("%f",&p1->Pos);         printf("请输入第%d架信号机的闭锁继电器状态：\n",i_count+1);         fflush(stdout);rewind(stdin);         scanf("%d",&p1->Type);//输入后点击两次回车。         pr->next=p1;         pr=p1;         i_count++;         printf("是否继续(T/F)\n");         fflush(stdout);rewind(stdin);         scanf("%c",&answer);     } }   void Change(struct Signal *head) {     char s[20];     struct Signal* buf;     if(head==NULL) return;     printf("\t请输入想修改的信号机名称:");     scanf("%s",s);     buf=head->next;     while(strcmp(buf->Name,s)!=0 && buf->next!=NULL)     {            buf=buf->next;//找到要修改的信号机     }     if(buf==NULL || strcmp(buf->Name,s)!=0)     {         printf("\t没有这个信号机!\n");         return;     }else{         //输入修改之后的数据         printf("\t信号机名称改为:");         scanf("%s",buf->Name);         printf("\t信号机开放状态改为:");         scanf("%d",&buf->KB);         printf("\t信号机位置改为:");         scanf("%f",&buf->Pos);         printf("\t信号机性质改为:");         scanf("%d",&buf->Type);         printf("\t修改成功!\n");     } } void change(struct Signal* head) {         if(head==NULL)  return;         printf("信号机名称\t信号机开放状态\t信号机位置\t信号机性质\n");         struct Signal *buf;         buf = head->next;         while(buf!=NULL)   // 输出全部信息         {              printf("%5s%15d%15g%15d\n",buf->Name,buf->KB,buf->Pos,buf->Type);//输出信息              buf=buf->next;         } }  void delete_xinhaoji(struct Signal*head) {     if(head==NULL) return;     char Signal_num[20];     printf("\t请输入要删除的信号机的名称:");     scanf("%s",Signal_num);     struct Signal*tmp,*pre;     for(tmp=head->next,pre=head;tmp!=NULL;pre=tmp,tmp=tmp->next)     {         if(strcmp(tmp->Name,Signal_num)==0)         {            pre->next=tmp->next;            free(tmp);//释放temp所占用的内存；            printf("\t\t\t删除信号机成功！\n");            i_count--;            return ;         }     }     if(tmp==NULL)     {         printf("\t无此信号机！\n");     } }  void chaxun(struct Signal*head) {     char s[10];     struct Signal*temp;     if(head==NULL) return;     printf("请输入想查询的信号机名称:\n");     scanf("%s",s);     temp=head->next;     while(strcmp(temp->Name,s)!=0 && temp->next!=NULL)     {         temp=temp->next;     }     if(temp==NULL || strcmp(temp->Name,s)!=0)     {         printf("\t没有这个信号机!\n");     }     else     {         printf("\t此信号机名称:             %s\n",temp->Name);         printf("\t此信号机的位置是          %d\n",temp->KB);         printf("\t此信号机的开放状态是      %g\n",temp->Pos);         printf("\t此信号机的闭锁继电器状态是%d\n",temp->Type);     } }    void read(struct Signal*&head)//将文件中的内容读出到链表中，返回值为表头地址 {     FILE *fp; //文件指针     char filename[32]="signal.txt";     struct Signal *p,*p1,*pr=NULL;     //printf("请输入打开的文件名(signal.txt):");     //scanf("%s",filename);     if((fp=fopen(filename,"r+"))==NULL)//以二进制的方式打开文件     {         printf("cannot open file\n");//如有错则输出cannot open file         return;//exit(0);     }     if(head==NULL)     {             head=(struct Signal*)malloc(sizeof(struct Signal));             if(!head)  return;             head->next=NULL;     }     pr=head;     p1=head->next;     while(p1){pr=p1; p1=p1->next;}     while(1)     {            p=(struct Signal*)malloc(sizeof(struct Signal));            p->next=NULL;            if(fscanf(fp,"%s %d %f %d",p->Name,&p->KB,&p->Pos,&p->Type)!=4) break;            pr->next=p;            pr=p;            i_count++;     }     fclose(fp);    //关闭文件 }  void write(struct Signal *head) {         struct Signal*p;         FILE *fp;         int  i=0 ;         char filename[32]="signal.txt";         p=head->next;         //printf("请输入保存的文件名(signal.txt):");         //scanf("%s",filename);         if((fp=fopen(filename,"w+"))==NULL)         {                printf("不能打开文件\n");                return;         }         while(p!=NULL)         {                fprintf(fp,"%5s\t%15d\t%15f\t%15d\n",p->Name,p->KB,p->Pos,p->Type);                p=p->next;                i++;         }         //fprintf(fp,"-------------------------------------------------------------------------\n");         //fprintf(fp,"*****共有%d个信号机*****\n",i);         fclose(fp);                  //关闭文件         printf("保存成功!\n"); }  void myfree(struct Signal*head) {     struct Signal*p=NULL;     for(;head!=NULL;)     {         p=head;         head=head->next;         free(p);     }     i_count=0;     system("pause"); }  int main() {     int option;     read(head);//系统起始，载入文件信息。     while (1)     {         system("cls");         printf("    主菜单：\n");         printf("1,  添加信号机：    \n");         printf("2,  查看信号机：    \n");         printf("3,  修改信号机信息：\n");         printf("4,  删除信号机：    \n");         printf("5,  保存信号机信息：\n");         printf("6,  浏览信号机信息：\n");         printf("7,  保存并退出系统：\n");         printf("请选择：            \n");         scanf("%d",&option);         getchar();         switch(option)         {             case 1:creat(head); break;             case 2:chaxun(head);break;             case 3:Change(head);break;//修改信号机信息             case 4:delete_xinhaoji(head);break;             case 5://write(head);                    break;             case 6:change(head);break;//浏览信号机信息             case 7:write(head);free(head);exit(0);             default:printf("enter data error!\n");         }         system("pause");     }     return 0; }

这个还是只编译成功了但是各部分功能还是没办法运行啊

什么功能没办法运行？我把文件读入功能，放在了系统启动时自动加载了，文件保存放在了第7项里了，退出系统前先保存到文件里。所以系统运行时，菜单里的保存信号机信息到文件第5项就给屏蔽了，第6项 读取文件内容改成了浏览信号机信息了。

编译成功了并不代表没有错误，比如这一行：  while (option=6)  很显然就是一个错误。等你把这些错误改完了再说吧！

我在赵四老师改的基础上又改了一下，现在错误应该差不多了，但是程序依然没发运行写入数据后只能保存一组数据，运行其他子程序时直接退出。现在应该怎么办。#include<stdio.h> #include<stdlib.h> #include<string.h> #include <time.h> struct Signal  {     char Name[10];    //名字     int KB;            //开放状态     float Pos;        //地址     int Type;            //闭锁継电器状态     struct Signal *next,*front; }; struct Signal*head; void write(); void read(); void creat(); void chaxun(); void change(); void Change(); void delete_xinhaoji(); void myfree();     void creat() {     int n,i=0;     char answer=' ';     struct Signal*p1,*p2;     n=0;     p1=p2=(struct Signal*)malloc(sizeof(struct Signal));     p1->Pos=1.0;     printf("请输入第1架信号机的名称：\n");     scanf("%s",p1->Name);     printf("请输入第1架信号机的开放状态:\n");     scanf("%d",&p1->KB);     printf("请输入第1架信号机的地址:\n");     scanf("%f",&p1->Pos);     printf("请输入第1架信号机的闭锁继电器状态\n");     scanf("%d",&p1->Type);     head=NULL;     while(answer!='F'&&answer!='f')     {         n=n+1;         if(n==1)  		{             head=p1;         }  		else  		{             p2->next=p1;         }         p2=p1;         p1=(struct Signal*)malloc(sizeof(struct Signal));         getchar();         printf("请输入第%d架信号机的名称：\n",i+2);         scanf("%s",p1->Name);         printf("请输入第%d架信号机的开放状态：\n",i+2);         scanf("%d",&p1->KB);         printf("请输入第%d架信号机的地址：\n",i+2);         scanf("%f",&p1->Pos);         printf("请输入第%d架信号机的闭锁继电器状态：\n",i+2);         scanf("%d",&p1->Type);//输入后点击两次回车。         getchar();         i++;         getchar();         printf("是否继续(T/F)\n");         scanf("%c",&answer);         getchar();     }     p2->next=NULL; }    void change()  { 	struct Signal*buf;     printf("%5s%15d%15g%15d\n",head->Name,&head->KB,&head->Pos,&head->Type);          while(1)     {         printf("%5s%15d%15g%15d\n",head->Name,&head->KB,&head->Pos,&head->Type);           buf = head->next;         while(buf!=NULL)        // 输出全部信息         {             printf("%5s%15d%15g%15d\n",buf->Name,&buf->KB,&buf->Pos,&buf->Type);   // 输出信息             buf=buf->next;         }         Change();     } } void Change()  { 	struct Signal* buf;     char s[20];     buf=head->next;     printf("\t请输入想修改的信号机:");     scanf("%s",s);     while(strcmp(buf->Name,s)!=0&&buf!=NULL) buf=buf->next;//找到要修改的信号机     if(buf==NULL)     {         printf("\t没有这个信号机!\n");         return;     }     //输入修改之后的数据     printf("\t信号机名称:");     scanf("\t%s",buf->Name);     printf("\t信号机开放状态:");     scanf("\t%d",&buf->KB);     printf("\t信号机位置:");     scanf("\t%f",&buf->Pos);     printf("\t信号机性质:");     scanf("\t%d",&buf->Type);     printf("\t修改成功!\n"); }    void delete_xinhaoji()  { 	struct Signal*temp;     char Signal_num[20];     printf("\t请输入要删除的信号机的名称:");     scanf("%s",Signal_num);     for(temp=head->next;temp!=NULL;temp=temp->next)     {         if(strcmp(temp->Name,Signal_num)==0)         {             // 找到需要删除节点的位置             struct Signal*front=temp->front;             struct Signal*next=temp->next;             //进行删除操作；             front->next=next;             next->front=front;             free(temp);//释放temp所占用的内存；             printf("\t\t\t删除信号机成功！\n");             return ;         }     }     if(temp==NULL)     {         printf("\t无此信号机！\n");     } }       void chaxun() {     char s[10];     struct Signal*temp=head->next;     printf("请输入想查询的信号机\n");     scanf("%s",s);     while(strcmp(temp->Name,s)!=0&&temp->next!=NULL)     {         temp=temp->next;     }     if(strcmp(temp->Name,s)!=0)     {         printf("\t没有这个信号机!\n");         return;     } else {         printf("\t此信号机名称:%s\n",temp->Name);         printf("\t此信号机的位置是%d\n",temp->KB);         printf("\t此信号机的开放状态是%g\n",temp->Pos);         printf("\t此信号机的闭锁继电器状态是%d\n",temp->Type);     } }    void read() {     //将文件中的内容读出到链表中，返回值为表头地址     FILE *fp;       //文件指针     int n=0;     char filename[10];     struct Signal*p2,*p,*pr=NULL;     printf("请输入需要打开的文件");     scanf("%s",filename);     if((fp=fopen(filename,"r+"))==NULL)     //以二进制的方式打开文件     {         printf("cannot open file\n");//如有错则输出cannot open file         exit(0);     }     while(!feof(fp))        //判断文件位置标志是否移动到文件末尾     {         n++;         p=(struct Signal*)malloc(sizeof(struct Signal));         fscanf(fp,"%s%d%f%d",p->Name,&p->KB,&p->Pos,&p->Type);         if(n==1)    {             head=p;             p2=p;         } else {             //创建链表             pr=p2;             p2->next=p;             p2=p;         }     }     if(pr!=NULL)     {        pr->next=NULL;     } else {        head=NULL;     }     fclose(fp);    //关闭文件 }    void write()  {     struct Signal*p;     FILE *fp;     int  i=0 ;     char filename[10];     p=head;     printf("请输入需要打开的文件");     scanf("%s",filename);     if((fp=fopen(filename,"w+"))==NULL)     {         printf("不能打开文件\n");         return;     }     while(p!=NULL)     {         fprintf(fp,"%5s\t%15d\t%15f\t%15d\n",p->Name,p->KB,p->Pos,p->Type);         p=p->next;         i++;     }     fprintf(fp,"-------------------------------------------------------------------------\n");     fprintf(fp,"*****共有%d个信号机*****\n",i);     fclose(fp);                  //关闭文件     printf("保存成功!\n"); }       void myfree()  {     struct Signal*p=NULL;     for(;head!=NULL;)     {         p=head;         head=head->next;         free(p);     }     system("pause"); } 	int main()  	{     int option;     while (1)     {         system("cls");         printf("    主菜单：\n");         printf("1,  添加信号机：    \n");         printf("2,  查看信号机：    \n");         printf("3,  修改信号机信息：\n");         printf("4,  删除信号机：    \n");  		printf("5, 保存信号机信息：\n"); 		printf("6, 读入信号机信息，\n"); 		printf("7, 退出菜单 \n"); 		printf("请选择： \n"); 		scanf("%d",&option); 		getchar(); 		switch(option)  		{  			case 1:creat(); break;  			case 2:chaxun(); break;  			case 3:change(); break;  			case 4:delete_xinhaoji();break;  			case 5:write(); break;  			case 6:read(); break;  			case 7:myfree(); exit(0);  			default:printf("enter data error!\n");  		}  	}  	return 0;  }

喏，出现了这么多错误！要对着错误修改！https://wandbox.org/permlink/fJaSf3mv7oG8e6aV prog.cc: In function 'void change(Signal*)': prog.cc:113:23: error: too many arguments to function 'void Change()'   113 |                 Change(head);       |                 ~~~~~~^~~~~~ prog.cc:75:6: note: declared here    75 | void Change()       |      ^~~~~~ prog.cc:102:19: warning: unused variable 'temp' [-Wunused-variable]   102 |     struct Signal*temp,*buf;       |                   ^~~~ prog.cc: In function 'void chaxun(Signal*)': prog.cc:153:9: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'char (*)[10]' [-Wformat=]   153 | scanf("%s",&s);       |        ~^  ~~       |         |  |       |         |  char (*)[10]       |         char* prog.cc: In function 'void read(Signal*)': prog.cc:183:17: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'char (*)[10]' [-Wformat=]   183 |         scanf("%s",&filename);       |                ~^  ~~~~~~~~~       |                 |  |       |                 |  char (*)[10]       |                 char* prog.cc:184:35: error: cannot convert 'bool' to 'FILE*' in assignment   184 |         if(fp=fopen(filename,"r+")==NULL);     //以二进制的方式打开文件       |                                   ^       |                                   |       |                                   bool prog.cc:184:42: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]   184 |         if(fp=fopen(filename,"r+")==NULL);     //以二进制的方式打开文件       |                                          ^ prog.cc:184:9: warning: this 'if' clause does not guard... [-Wmisleading-indentation]   184 |         if(fp=fopen(filename,"r+")==NULL);     //以二进制的方式打开文件       |         ^~ prog.cc:185:9: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'   185 |         {       |         ^ prog.cc:192:27: warning: format '%d' expects argument of type 'int*', but argument 4 has type 'int' [-Wformat=]   192 |            fscanf(fp,"%s,%d,%f,%d",p->Name,p->KB,p->Pos,p->Type);       |                          ~^                ~~~~~       |                           |                   |       |                           int*                int prog.cc:192:30: warning: format '%f' expects argument of type 'float*', but argument 5 has type 'double' [-Wformat=]   192 |            fscanf(fp,"%s,%d,%f,%d",p->Name,p->KB,p->Pos,p->Type);       |                             ~^                   ~~~~~~       |                              |                      |       |                              float*                 double prog.cc:192:33: warning: format '%d' expects argument of type 'int*', but argument 6 has type 'int' [-Wformat=]   192 |            fscanf(fp,"%s,%d,%f,%d",p->Name,p->KB,p->Pos,p->Type);       |                                ~^                       ~~~~~~~       |                                 |                          |       |                                 int*                       int prog.cc: In function 'void write(Signal*)': prog.cc:227:25: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'char (*)[10]' [-Wformat=]   227 |                 scanf("%s",&filename);       |                        ~^  ~~~~~~~~~       |                         |  |       |                         |  char (*)[10]       |                         char* prog.cc: In function 'int main()': prog.cc:266:22: warning: suggest parentheses around assignment used as truth value [-Wparentheses]   266 |         while (option=6)       |                ~~~~~~^~

这个在Dev上是可以编译成功的，只有一个错误

#include<stdio.h> #include<stdlib.h> #include<string.h> #include <time.h> struct Signal {     char Name[10];    //名字     int KB;            //开放状态     float Pos;        //地址     int Type;            //闭锁継电器状态     struct Signal *next,*front; }; struct Signal*head; void write(); void read(); void creat(); void chaxun(); void change(); void Change(); void delete_xinhaoji(); void myfree();  void creat() {     int n,i=0;     char answer=' ';     struct Signal*p1,*p2;     n=0;     p1=p2=(struct Signal*)malloc(sizeof(struct Signal));     p1->Pos=1.0;     printf("请输入第1架信号机的名称：\n");     scanf("%s",p1->Name);     printf("请输入第1架信号机的开放状态:\n");     scanf("%d",&p1->KB);     printf("请输入第1架信号机的地址:\n");     scanf("%f",&p1->Pos);     printf("请输入第1架信号机的闭锁继电器状态\n");     scanf("%d",&p1->Type);     head=NULL;     while(answer!='F'&&answer!='f')     {         n=n+1;         if(n==1) {             head=p1;         } else {             p2->next=p1;         }         p2=p1;         p1=(struct Signal*)malloc(sizeof(struct Signal));         getchar();         printf("请输入第%d架信号机的名称：\n",i+2);         scanf("%s",p1->Name);         printf("请输入第%d架信号机的开放状态：\n",i+2);         scanf("%d",&p1->KB);         printf("请输入第%d架信号机的地址：\n",i+2);         scanf("%f",&p1->Pos);         printf("请输入第%d架信号机的闭锁继电器状态：\n",i+2);         scanf("%d",&p1->Type);//输入后点击两次回车。         getchar();         i++;         getchar();         printf("是否继续(T/F)\n");         scanf("%c",&answer);         getchar();     }     p2->next=NULL; }  void Change() {     char s[20];     struct Signal* buf;     buf=head->next;     printf("\t请输入想修改的信号机:");     scanf("%s",s);     while(strcmp(buf->Name,s)!=0&&buf!=NULL) buf=buf->next;//找到要修改的信号机     if(buf==NULL)     {         printf("\t没有这个信号机!\n");         return;     }     //输入修改之后的数据     printf("\t信号机名称:");     scanf("\t%s",buf->Name);     printf("\t信号机开放状态:");     scanf("\t%d",&buf->KB);     printf("\t信号机位置:");     scanf("\t%f",&buf->Pos);     printf("\t信号机性质:");     scanf("\t%d",&buf->Type);     printf("\t修改成功!\n"); } void change() {     printf("%5s%15d%15g%15d\n",head->Name,head->KB,head->Pos,head->Type);     struct Signal *buf;     while(1)     {         printf("%5s%15d%15g%15d\n",head->Name,head->KB,head->Pos,head->Type);          buf = head->next;         while(buf!=NULL)        // 输出全部信息         {             printf("%5s%15d%15g%15d\n",buf->Name,buf->KB,buf->Pos,buf->Type);   // 输出信息             buf=buf->next;         }         Change();     } } void delete_xinhaoji() {     char Signal_num[20];     printf("\t请输入要删除的信号机的名称:");     scanf("%s",Signal_num);     struct Signal*temp;     for(temp=head->next;temp!=NULL;temp=temp->next)     {         if(strcmp(temp->Name,Signal_num)==0)         {             // 找到需要删除节点的位置             struct Signal*front=temp->front;             struct Signal*next=temp->next;             //进行删除操作；             front->next=next;             next->front=front;             free(temp);//释放temp所占用的内存；             printf("\t\t\t删除信号机成功！\n");             return ;         }     }     if(temp==NULL)     {         printf("\t无此信号机！\n");     } }  void chaxun() {     char s[10];     struct Signal*temp=head->next;     printf("请输入想查询的信号机\n");     scanf("%s",&s);     while(strcmp(temp->Name,s)!=0&&temp->next!=NULL)     {         temp=temp->next;     }     if(strcmp(temp->Name,s)!=0)     {         printf("\t没有这个信号机!\n");         return;     } else {         printf("\t此信号机名称:%s\n",temp->Name);         printf("\t此信号机的位置是%d\n",temp->KB);         printf("\t此信号机的开放状态是%g\n",temp->Pos);         printf("\t此信号机的闭锁继电器状态是%d\n",temp->Type);     } }  void read() {     //将文件中的内容读出到链表中，返回值为表头地址     FILE *fp;       //文件指针     int n=0;     char filename[10];     struct Signal*p2,*p,*pr=NULL;     printf("请输入需要打开的文件");     scanf("%s",&filename);     if((fp=fopen(filename,"r+"))==NULL)     //以二进制的方式打开文件     {         printf("cannot open file\n");//如有错则输出cannot open file         exit(0);     }     while(!feof(fp))        //判断文件位置标志是否移动到文件末尾     {         n++;         p=(struct Signal*)malloc(sizeof(struct Signal));         fscanf(fp,"%s%d%f%d",p->Name,p->KB,p->Pos,p->Type);         if(n==1)    {             head=p;             p2=p;         } else {             //创建链表             pr=p2;             p2->next=p;             p2=p;         }     }     if(pr!=NULL)     {        pr->next=NULL;     } else {        head=NULL;     }     fclose(fp);    //关闭文件 } void write() {     struct Signal*p;     FILE *fp;     int  i=0 ;     char filename[10];     p=head;     printf("请输入需要打开的文件");     scanf("%s",&filename);     if((fp=fopen("filename","w+"))==NULL)     {         printf("不能打开文件\n");         return;     }     while(p!=NULL)     {         fprintf(fp,"%5s\t%15d\t%15f\t%15d\n",p->Name,p->KB,p->Pos,p->Type);         p=p->next;         i++;     }     fprintf(fp,"-------------------------------------------------------------------------\n");     fprintf(fp,"*****共有%d个信号机*****\n",i);     fclose(fp);                  //关闭文件     printf("保存成功!\n"); }  void myfree() {     struct Signal*p=NULL;     for(;head!=NULL;)     {         p=head;         head=head->next;         free(p);     }     system("pause"); } int main() {     int option;     while (option=6)     {         system("cls");         printf("    主菜单：\n");         printf("1,  添加信号机：    \n");         printf("2,  查看信号机：    \n");         printf("3,  修改信号机信息：\n");         printf("4,  删除信号机：    \n");         printf("5,  保存信号机信息：\n");         printf("6,  读入信号机信息，\n");         printf("7,  退出菜单        \n");         printf("请选择：            \n");         scanf("%d",&option);         getchar();         switch(option)         {             case 1:creat();          break;             case 2:chaxun();         break;             case 3:change();         break;             case 4:delete_xinhaoji();break;             case 5:write();          break;             case 6:read();           break;             case 7:myfree();         exit(0);             default:printf("enter data error!\n");         }     }     return 0; }

虽然编译成功了但是功能依然实现不了，输入数据后保存只能保存第一串数据，而且其他像其他程序运行的时候会一直出现这个问题，Process exited after 41.71 seconds with return value 3221225477 请按任意键继续. . .。我觉得是指针的问题，但是又不知道怎么改。

有时候还会出现这个错误，	[Error] ld returned 1 exit status


Question: C语言中如何处理0x00?

仅供参考： #include <string.h> FILE *f; char buffer[4096]; int r,a; void HexDump(char *buf,int len,int addr) {     int i,j,k;     char binstr[80];      for (i=0;i<len;i++) {         if (0==(i%16)) {             sprintf(binstr,"%08x -",i+addr);             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         } else if (15==(i%16)) {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);             sprintf(binstr,"%s  ",binstr);             for (j=i-15;j<=i;j++) {                 sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');             }             printf("%s\n",binstr);         } else {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         }     }     if (0!=(i%16)) {         k=16-(i%16);         for (j=0;j<k;j++) {             sprintf(binstr,"%s   ",binstr);         }         sprintf(binstr,"%s  ",binstr);         k=16-k;         for (j=i-k;j<i;j++) {             sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');         }         printf("%s\n",binstr);     } } int main(int argc,char **argv) {     if (argc<2) {         fprintf(stderr,"Usage: %s filename.ext\n",argv[0]);         return 2;     }     f=fopen(argv[1],"rb");     if (NULL==f) {         fprintf(stderr,"Can not open file [%s]!\n",argv[1]);         return 1;     }     a=0;     while (1) {         r=fread(buffer,1,4096,f);         HexDump(buffer,r,a);         a+=r;         if (r<4096) break;     }     fclose(f);     return 0; }

非常感谢赵老师的解答^_^

fscanf %x，使用长度再做一个循环；

按二进制读取，而不是按文本读取


看看ioctrl的定义和实现，有的只需要少量的参数，有的需要多个参数。一般来说，需要多个参数，而且参数数据较大时，很有可能需要copy_from_user。

要看对应的调用要不要求读写的内存必须是内核内存管理模块管理下的内存。我猜


Question: 将其中连续的多个空格用一个空格代替 ,用while遍历空格，最后只输出一个空格，如下代码为何不可？

putchar->printf

对，无法输出空格，并且应该赋值号，不应该为等号

你putchar(c);只有在c != ' '的情况下才执行，这样就一次也不输出空格了。


Question: 求求各位大神指点错误，如何改错？（Dev c++软件）

第136行，文件保存：ofstream outfile(cust[i].name+".txt",ios::out);      修改为：               ofstream outfile((cust[i].name+".txt").c_str(),ios::out);


Question: 关于C语言全局变量问题

你不是说第二个（项目4）makefile可以执行吗。你的makefile中没有a.c和b.c的编译规则，最后链接也没有包含a.o和b.o。

不太懂makefile ,b.o应该不用写，另外b.o依赖的是b.h，而不是b.c


Question: 这个程序输入时只能输入两串数据，之后就会直接结束，现在知道错误在调用write()函数中，但是不知道具体错误，也不知道怎么改。

修改如下，供参考：  #include<stdio.h> #include<stdlib.h> #include<string.h>  struct Signal {     char   Name[10];     int    KB;     float  Pos;     int    Type;     struct Signal *next,*front; }; int n=0,i=0; char ch=0;  void write(struct Signal*head);  int main() {         struct Signal *head=NULL;         struct Signal *p1,*p2;         while(1)         {               p1=(struct Signal*)malloc(sizeof(struct Signal));               if(!p1)  return 1;               p1->next=NULL;               printf("请输入第%d架信号机的信息\n",++i);               scanf("%s",p1->Name);               if(strcmp(p1->Name,"#")==0)  break; //"#"结束输入               scanf("%d %f %d",&p1->KB,&p1->Pos,&p1->Type);               n++;               if(n==1){                        head=p1;               }else{                        p2->next=p1;               }               p2=p1;               //write(head);         }         free(p1);         write(head);                  return 0;//return (head); }  void write(struct Signal*head) {         struct Signal*p;         FILE *fp;         int  i=0 ;         p=head;         if((fp=fopen("ABC.txt","w+"))==NULL)         {                printf("不能打开文件\n");                return;         }         while(p!=NULL)         {                fprintf(fp,"%5s\t%15d\t%15g\t%15d\n",p->Name,p->KB,p->Pos,p->Type);                p=p->next;                i++;         }         fprintf(fp,"-------------------------------------------------------------------------\n");         fprintf(fp,"*****共有%d个信号机*****\n",i);         fclose(fp);                  //关闭文件         printf("保存成功!\n"); }

谢谢


Question: 求助：[Error] expected primary-expression before ';' token

第56 59 69行都是同样错误，行末尾 '<<;' ，应该改为：<<endl;

感谢您，问题解决了。


Question: ReadDirectoryChangesW 监听目录 丢失消息的问题

问题已解决：https://bbs.csdn.net/topics/600348125

"d:/zhouhui/c", 这里的写法错误了： #include <stdio.h> #include <windows.h> #include <string.h>  int main() {     HANDLE handle = CreateFile(         "d:\\zhouhui",   //这里的目录字段格式错误         GENERIC_READ,         FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,         NULL,         OPEN_EXISTING,         FILE_FLAG_BACKUP_SEMANTICS,         NULL     );     FILE_NOTIFY_INFORMATION pNotify[1024] = {0};     LPDWORD lpBytesReturned;     int i = 0;     while(1)     {         ReadDirectoryChangesW(             handle,             pNotify,             1024, //The size of the buffer             TRUE,//bWatchSubtree,             FILE_NOTIFY_CHANGE_FILE_NAME,//FILE_NOTIFY_CHANGE_DIR_NAME             (LPDWORD)& lpBytesReturned,   //lpBytesReturned             NULL,      //lpOverlapped             NULL         );         i++;         printf("%d\n",i);         } }

这跟目录格式没关系的呀，都能监听到的

有关系，"d:/zhouhui/c"这个形式，我的电脑上就死循环了。

好吧，那你改成那样子后，多试几次，会有遗漏消息吗？

while(1)     {             ReadDirectoryChangesW(             handle,              pNotify,             5000, //The size of the buffer             TRUE,//bWatchSubtree,             FILE_NOTIFY_CHANGE_FILE_NAME,//FILE_NOTIFY_CHANGE_DIR_NAME             (LPDWORD)& lpBytesReturned,   //lpBytesReturned             NULL,      //lpOverlapped             NULL         );                  DWORD dw = 0;             FILE_NOTIFY_INFORMATION* p;                  do {             p = &pNotify[dw];                          i++;                      printf("%d\n",i);                          dw += p->NextEntryOffset;         }         while(p->NextEntryOffset !=0);     }   网上有说要循环  FILE_NOTIFY_INFORMATION 链表的，我也照着做了，可还是会丢呢（如下图，添加时是10个，删除时，却只出来3个）。

这是我刚刚又测试的，往里面放10张图片，然后又删除这个文件夹，结果只输出几次。。。


Question: 这个开源文本识别系统我粉了（附源码）

新版没有表情了


Question: 求助 C动态内存问题

p=(int *)realloc(p,SIZE*2*sizeof(int));

谢谢！正常输出了


Question: 求助 老师给出的题

这代码逻辑混乱不堪，问题多多，这个能当题目也是醉了fission函数返回应该是个指针，因此int s[10]需要定义为static的，或者直接定义为全局变量，s里的内容没初始化。。。。


Question: 求一个list保存的数据 ，计算与判断方式的算法。

了解一下“有限状态自动机”

好的  谢谢了


Question: 急求解

用排序的方法是可以的，但是效率不是最优，可以用这个比较好的方法，遍历一次就可以了。 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(void) {     int score[100], i, cnt = 0;     int max[3]; for (i = 0; i < 100; i++) {     if (scanf("%d", &score[i]) && score[i] >= 0) {         cnt++;         continue;     }     break; }  max[0] = max[1] = max[2] = -1; for (i = 0; i < cnt; i++) {     if (score[i] > max[0]) {         max[2] = max[1];         max[1] = max[0];         max[0] = score[i];     } else if (score[i] > max[1]){         max[2] = max[1];         max[1] = score[i];     } else if (score[i] > max[2]) {         max[2] = score[i];     } }  printf("%d,%d,%d\n", max[0], max[1], max[2]);  return 0;  }  ```#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h>  int main(void) {     int score[100], i, cnt = 0;     int max[3];      for (i = 0; i < 100; i++) {         if (scanf("%d", &score[i]) && score[i] >= 0) {             cnt++;             continue;         }         break;     }      max[0] = max[1] = max[2] = -1;     for (i = 0; i < cnt; i++) {         if (score[i] > max[0]) {             max[2] = max[1];             max[1] = max[0];             max[0] = score[i];         } else if (score[i] > max[1]){             max[2] = max[1];             max[1] = score[i];         } else if (score[i] > max[2]) {             max[2] = score[i];         }     }      printf("%d,%d,%d\n", max[0], max[1], max[2]);      return 0; }

录入的时候就可以找前三大了，可以优化不用两个循环

这个就是排序吧，很简答的吧。你是想知道思路还是代码


Question: 急求解！！

供参考： #include<stdio.h>  int main() {     double S=1.0,eps,tmp=1.0;     int    N=1;     scanf("%lf",&eps);     while(tmp >= eps){           tmp *= 1.0/N;           S += tmp;           N ++;     }     printf("e=%.3f,count=%d\n",S,N);         return 0; }


Question: 输出上三角数字阵列.求解急

供参考： #include<stdio.h> int main() {     int i,j,n,m;     scanf("%d%d",&n,&m);     for(i=n-1;i>=0;i--)     {         for(j=0;j<=i;j++)         {             printf("%-4d",m++);         }         printf("\n");     }          return 0; }


Question: 这个错误怎么改

#include<stdio.h> #include<stdlib.h> int option; void AddNew() {     //TODO } void FindMenu() {     //TODO } void ModifyData() {     //TODO } void Delete() {     //TODO } void MainMenu() {     system("cls");     printf("主菜单：\n");     printf("1,  添加信号机：    \n");     printf("2,  查看信号机：    \n");     printf("3,  修改信号机信息：\n");     printf("4,  删除信号机：    \n");     printf("5,  退出程序：      \n");     printf("请选择：            \n");     scanf("%d",&option);     getchar(); } int main() {     MainMenu();     switch (option)     {     case 1:AddNew()        ;break;     case 2:FindMenu()    ;break;     case 3:ModifyData()    ;break;     case 4:Delete()        ;break;     case 5:exit(0);     }     return 0; }

嗯，谢谢“赵4老师”。


Question: 小白求一段字符串截取方法。

#include <stdio.h> #include <string.h> int main() {     char p[]="/data/detect/20210630/OPIA2021063099459/f93fb93a70ee4f048f3e35445d10fd57.jpg";     char *q;     q=strrchr(p,'/');     if (q) {         q[1]=0;         printf("%s\n",p);// "/data/detect/20210630/OPIA2021063099459/"     } else {         printf("Can not find / in %s\n",p);     }     return 0; }

赵老师武威

要是可修改，就从后往前查找 / 字符，然后把它后面一个位置赋值为'\0'。


Question: 求助一道strout strerr问题

因为stout和stderr是两个不同的输出管道，且输出字符串没有以'\n'结尾且没有fflush,输出都被缓存在各自管道的内部缓冲区中，直到程序退出前，输出缓冲区中的信息才会被flush而一起显示。

感谢！


只需遍历2 ~ sqrt(n)之间的整数去除就可以了

供参考：  #include<stdio.h>  int f(int);   int main() {     int a,b,count,s,c,i;     scanf("%d %d",&a,&b);     count=0;     s=0;     for(i=a;i<=b;i++){         if(f(i)!=0){             count++;             s += i;         }     }     printf("%d %d\n",count,s);          return 0; }   int f(int n) {     int i;     if(n <= 3) return n>1;     for(i=2;i*i <= n;i++)        if(n%i == 0) return 0;     return 1; }

大概不是错了，而是慢了吧？


Question: 为什么保存到文件的数据不是十进制的

两次打开文件； 写文件时那些变量取地址干嘛； 第四个格式符也不对，那是浮点的。

你所指的十进制可能是想保存的文本文件看起来和输入的一样吧，是这样的话，保存时必须把数据转换成字符或字符串再按字符串保存，正常情况保存，都是二进制的，比如 字母 '1'  保存时值是49，十六进制为31，虽然你保存的文件指定后缀名为.txt,但值不会自动为你变成文本. 数字123 ,保存时就是31 32 33 ，保存到文本文件看起来要是123，那就要转换成字符串再保存，读取回来时也要将字符串“123” 转换成数字123

电脑内存或文件内容或传输内容只是一个一维二进制字节数组及其对应的二进制地址； 人脑才将电脑内存或文件内容或传输内容中的这个一维二进制字节数组及其对应的二进制地址的某些部分看成是整数、有符号数/无符号数、浮点数、复数、英文字母、阿拉伯数字、中文/韩文/法文……字符/字符串、汇编指令、函数、函数参数、堆、栈、数组、指针、数组指针、指针数组、数组的数组、指针的指针、二维数组、字符点阵、字符笔画的坐标、黑白二值图片、灰度图片、彩色图片、录音、视频、指纹信息、身份证信息……   推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。


Question: c语言如何让一组数据跟着另一组数据变动

把代码贴上来，才可以帮到你。

给学生排名时，如何让每个人各科的成绩与他们的总成绩相对应，（每次我把总成绩排出来了，但是每个人的成绩没有变),设置一个结构体变量 struct student temp;  ，然后整体搬迁。

指针指向同一个实体。

不知道你问的是啥意思。


Question: 为什么我这个代码会缓冲区溢出想两天了

“多一少一”问题占程序员常犯错误的10%以上！ 避免“多一少一”问题的方法之一是将比如<10甚至<5的数代入程序片断，掰手指头心算验证一下程序到底应该写为 x、x-1、x+1中的哪个？ <、<=、==、>、>=中的哪个？

#include <stdio.h> #include <string.h> #define LEN 8 char * mystrncat(char*,char*,int); int main(void) {     char s1[LEN],s2[LEN];      while (fgets(s1,LEN,stdin)!=NULL&&(s1[0]!='\n')) {         fgets(s2,LEN,stdin);         printf("\n%s",mystrncat(s1,s2,LEN));     }     printf("Bye.\n");     return 0; } char * mystrncat(char*s1,char*s2,int n) {     char* ps=s1;      for (;*ps!='\n'&&*ps!='\0';ps++)         continue;      for(int i=0;i<=(n-1);i++,ps++)         *ps=s2[i];      *ps='\0';      return s1; } //1234 //abcde // //1234abcde // //Bye. //  显然结果超出了LEN个字符，即缓冲区溢出。

你从一个总长度80的数组中间某个位置开始写入80字节，溢出难道不是应该的么？


/*** *qsort.c - quicksort algorithm; qsort() library function for sorting arrays * *       Copyright (c) 1985-2001, Microsoft Corporation. All rights reserved. * *Purpose: *       To implement the qsort() routine for sorting arrays. * *******************************************************************************/  //#include <cruntime.h> #include <stdlib.h> #include <stdio.h> #include <search.h> //#include <internal.h>  /* Always compile this module for speed, not size */ #pragma optimize("t", on)  /* prototypes for local routines */ static void __cdecl shortsort(char *lo, char *hi, size_t width,                 int (__cdecl *comp)(const void *, const void *)); static void __cdecl swap(char *p, char *q, size_t width);  /* this parameter defines the cutoff between using quick sort and    insertion sort for arrays; arrays with lengths shorter or equal to the    below value use insertion sort */  #define CUTOFF 8            /* testing shows that this is good value */  /*** *qsort(base, num, wid, comp) - quicksort function for sorting arrays * *Purpose: *       quicksort the array of elements *       side effects:  sorts in place *       maximum array size is number of elements times size of elements, *       but is limited by the virtual address space of the processor * *Entry: *       char *base = pointer to base of array *       size_t num  = number of elements in the array *       size_t width = width in bytes of each array element *       int (*comp)() = pointer to function returning analog of strcmp for *               strings, but supplied by user for comparing the array elements. *               it accepts 2 pointers to elements and returns neg if 1<2, 0 if *               1=2, pos if 1>2. * *Exit: *       returns void * *Exceptions: * *******************************************************************************/  /* sort the array between lo and hi (inclusive) */  #define STKSIZ (8*sizeof(void*) - 2)  void __cdecl myqsort (     void *base,     size_t num,     size_t width,     int (__cdecl *comp)(const void *, const void *)     ) {     /* Note: the number of stack entries required is no more than        1 + log2(num), so 30 is sufficient for any array */     char *lo, *hi;              /* ends of sub-array currently sorting */     char *mid;                  /* points to middle of subarray */     char *loguy, *higuy;        /* traveling pointers for partition step */     size_t size;                /* size of the sub-array */     char *lostk[STKSIZ], *histk[STKSIZ];     int stkptr;                 /* stack for saving sub-array to be processed */      if (num < 2 || width == 0)         return;                 /* nothing to do */      stkptr = 0;                 /* initialize stack */      lo = (char *)base;     hi = (char *)base + width * (num-1);        /* initialize limits */      /* this entry point is for pseudo-recursion calling: setting        lo and hi and jumping to here is like recursion, but stkptr is        preserved, locals aren't, so we preserve stuff on the stack */ recurse:      int *p;     int i;     for (i=0,p=(int *)base;i<(int)num;i++,p++) printf("%d ",*p);     printf("\n");      size = (hi - lo) / width + 1;        /* number of el's to sort */      /* below a certain size, it is faster to use a O(n^2) sorting method */     if (size <= CUTOFF) {         shortsort(lo, hi, width, comp);     }     else {         /* First we pick a partitioning element.  The efficiency of the            algorithm demands that we find one that is approximately the median            of the values, but also that we select one fast.  We choose the            median of the first, middle, and last elements, to avoid bad            performance in the face of already sorted data, or data that is made            up of multiple sorted runs appended together.  Testing shows that a            median-of-three algorithm provides better performance than simply            picking the middle element for the latter case. */          mid = lo + (size / 2) * width;      /* find middle element */          /* Sort the first, middle, last elements into order */         if (comp(lo, mid) > 0) {             swap(lo, mid, width);         }         if (comp(lo, hi) > 0) {             swap(lo, hi, width);         }         if (comp(mid, hi) > 0) {             swap(mid, hi, width);         }          /* We now wish to partition the array into three pieces, one consisting            of elements <= partition element, one of elements equal to the            partition element, and one of elements > than it.  This is done            below; comments indicate conditions established at every step. */          loguy = lo;         higuy = hi;          /* Note that higuy decreases and loguy increases on every iteration,            so loop must terminate. */         for (;;) {             /* lo <= loguy < hi, lo < higuy <= hi,                A[i] <= A[mid] for lo <= i <= loguy,                A[i] > A[mid] for higuy <= i < hi,                A[hi] >= A[mid] */              /* The doubled loop is to avoid calling comp(mid,mid), since some                existing comparison funcs don't work when passed the same                value for both pointers. */              if (mid > loguy) {                 do  {                     loguy += width;                 } while (loguy < mid && comp(loguy, mid) <= 0);             }             if (mid <= loguy) {                 do  {                     loguy += width;                 } while (loguy <= hi && comp(loguy, mid) <= 0);             }              /* lo < loguy <= hi+1, A[i] <= A[mid] for lo <= i < loguy,                either loguy > hi or A[loguy] > A[mid] */              do  {                 higuy -= width;             } while (higuy > mid && comp(higuy, mid) > 0);              /* lo <= higuy < hi, A[i] > A[mid] for higuy < i < hi,                either higuy == lo or A[higuy] <= A[mid] */              if (higuy < loguy)                 break;              /* if loguy > hi or higuy == lo, then we would have exited, so                A[loguy] > A[mid], A[higuy] <= A[mid],                loguy <= hi, higuy > lo */              swap(loguy, higuy, width);              /* If the partition element was moved, follow it.  Only need                to check for mid == higuy, since before the swap,                A[loguy] > A[mid] implies loguy != mid. */              if (mid == higuy)                 mid = loguy;              /* A[loguy] <= A[mid], A[higuy] > A[mid]; so condition at top                of loop is re-established */         }          /*     A[i] <= A[mid] for lo <= i < loguy,                A[i] > A[mid] for higuy < i < hi,                A[hi] >= A[mid]                higuy < loguy            implying:                higuy == loguy-1                or higuy == hi - 1, loguy == hi + 1, A[hi] == A[mid] */          /* Find adjacent elements equal to the partition element.  The            doubled loop is to avoid calling comp(mid,mid), since some            existing comparison funcs don't work when passed the same value            for both pointers. */          higuy += width;         if (mid < higuy) {             do  {                 higuy -= width;             } while (higuy > mid && comp(higuy, mid) == 0);         }         if (mid >= higuy) {             do  {                 higuy -= width;             } while (higuy > lo && comp(higuy, mid) == 0);         }          /* OK, now we have the following:               higuy < loguy               lo <= higuy <= hi               A[i]  <= A[mid] for lo <= i <= higuy               A[i]  == A[mid] for higuy < i < loguy               A[i]  >  A[mid] for loguy <= i < hi               A[hi] >= A[mid] */          /* We've finished the partition, now we want to sort the subarrays            [lo, higuy] and [loguy, hi].            We do the smaller one first to minimize stack usage.            We only sort arrays of length 2 or more.*/          if ( higuy - lo >= hi - loguy ) {             if (lo < higuy) {                 lostk[stkptr] = lo;                 histk[stkptr] = higuy;                 ++stkptr;             }                           /* save big recursion for later */              if (loguy < hi) {                 lo = loguy;                 goto recurse;           /* do small recursion */             }         }         else {             if (loguy < hi) {                 lostk[stkptr] = loguy;                 histk[stkptr] = hi;                 ++stkptr;               /* save big recursion for later */             }              if (lo < higuy) {                 hi = higuy;                 goto recurse;           /* do small recursion */             }         }     }      /* We have sorted the array, except for any pending sorts on the stack.        Check if there are any, and do them. */      --stkptr;     if (stkptr >= 0) {         lo = lostk[stkptr];         hi = histk[stkptr];         goto recurse;           /* pop subarray from stack */     }     else         return;                 /* all subarrays done */ }   /*** *shortsort(hi, lo, width, comp) - insertion sort for sorting short arrays * *Purpose: *       sorts the sub-array of elements between lo and hi (inclusive) *       side effects:  sorts in place *       assumes that lo < hi * *Entry: *       char *lo = pointer to low element to sort *       char *hi = pointer to high element to sort *       size_t width = width in bytes of each array element *       int (*comp)() = pointer to function returning analog of strcmp for *               strings, but supplied by user for comparing the array elements. *               it accepts 2 pointers to elements and returns neg if 1<2, 0 if *               1=2, pos if 1>2. * *Exit: *       returns void * *Exceptions: * *******************************************************************************/  static void __cdecl shortsort (     char *lo,     char *hi,     size_t width,     int (__cdecl *comp)(const void *, const void *)     ) {     char *p, *max;      /* Note: in assertions below, i and j are alway inside original bound of        array to sort. */      while (hi > lo) {         /* A[i] <= A[j] for i <= j, j > hi */         max = lo;         for (p = lo+width; p <= hi; p += width) {             /* A[i] <= A[max] for lo <= i < p */             if (comp(p, max) > 0) {                 max = p;             }             /* A[i] <= A[max] for lo <= i <= p */         }          /* A[i] <= A[max] for lo <= i <= hi */          swap(max, hi, width);          /* A[i] <= A[hi] for i <= hi, so A[i] <= A[j] for i <= j, j >= hi */          hi -= width;          /* A[i] <= A[j] for i <= j, j > hi, loop top condition established */     }     /* A[i] <= A[j] for i <= j, j > lo, which implies A[i] <= A[j] for i < j,        so array is sorted */ }   /*** *swap(a, b, width) - swap two elements * *Purpose: *       swaps the two array elements of size width * *Entry: *       char *a, *b = pointer to two elements to swap *       size_t width = width in bytes of each array element * *Exit: *       returns void * *Exceptions: * *******************************************************************************/  static void __cdecl swap (     char *a,     char *b,     size_t width     ) {     char tmp;      if ( a != b )         /* Do the swap one character at a time to avoid potential alignment            problems. */         while ( width-- ) {             tmp = *a;             *a++ = *b;             *b++ = tmp;         } } int cmp(const void *pa, const void *pb) {     return *(int *)pa - *(int *)pb; } int main() {     int d[9]={12,5,9,20,6,31,24,27,13};     myqsort(&d[0],9,sizeof(int),cmp);     for (int i=0;i<9;i++) printf("%d ",d[i]);     return 0; } //12 5 9 20 6 31 24 27 13 //6 5 9 12 20 31 24 27 13 //5 6 9 12 20 31 24 27 13 //5 6 9 12 13 20 24 27 31 //


Question: Java泛型看不懂 求代码注释解释 急急急！！万分感谢ballball!!!

这里是C语言版面，这个问题应该发到Java版面去。


Question: 动态链表，有两个问题，能正常跑起来

经过大半天的调试，总算发现了问题，最大的问题在于creat()函数在初始化链表的时候，多了一个节点没有加入到链表的末尾，导致链表丢失NULL没法正常结束，从而导致输出最后一个数据的时候会卡顿0.5s左右。同时也导致了，输出函数末尾或者主函数输出函数后的换行符失效(可能是链表没有NULL，没能正常过结束)。调试后的代码就能正常了，也不会卡顿 #include<stdio.h> #include<stdlib.h>  //定义结构体 struct Joseph {     int People;     int Jundge;     struct Joseph *next; }; #define Len sizeof(struct Joseph) typedef struct Joseph SCJP; int n = 1; //建立动态链表。 struct Joseph *creat(void) {     struct Joseph *head = NULL;     struct Joseph *p1, *p2;     p1 = p2 = NULL;     printf("请输入总计有多少个人：");     int NumPeople = 0;     scanf_s("%d", &NumPeople);     rewind(stdin);     while (1)                //输入人数优化     {         if (NumPeople == 0 || NumPeople == 1)         {             printf("请重新输入：");             scanf_s("%d", &NumPeople);         }         else break;     }     p2 = p1 = (struct Joseph*)malloc(Len);     p1->People = n;     while (1)                    //循环优化     {         if (n == 1)head = p1;         else         {             p2->next = p1;         }         if (n == NumPeople)break;       //位置修改，原导致链表丢失NULL的判断语句，         p2 = p1;         p1 = (struct Joseph*)malloc(Len);         n++;         p1->People = n;     }     p1->next = NULL;     return(head); } int main(void) {     struct Joseph *p_head = NULL;     p_head = creat();     void Print_Link(struct Joseph *p);     Print_Link(p_head);     printf("\n");                        //原换行符无效的地方     free(p_head);     return 0; } //输出函数，检测输入人员编号是否有问题。 void Print_Link(struct Joseph *p) {     SCJP *Print_Temp = p;     int count = 1;     if (Print_Temp != NULL)     do{         printf(" %5d", Print_Temp->People);    //换行符在此有效，         if ((count++) % 15 == 0)             printf("\n");                             //原换行符无效的地方         //fflush(stdout);         Print_Temp = Print_Temp->next;     } while (Print_Temp != NULL);     fflush(stdout);     printf("\n");                                    //原换行符无效的地方     return; }     //fflush(stdout);     //printf("\n");                                    //原换行符无效的地方     return; }

不要使用 while (条件) 更不要使用 while (组合条件) 要使用 while (1) {  if (条件1) break;  //...  if (条件2) continue;  //...  if (条件3) return;  //... } 因为前两种写法在语言表达意思的层面上有二义性，只有第三种才忠实反映了程序流的实际情况。 典型如： 下面两段的语义都是当文件未结束时读字符 while (!feof(f)) {  a=fgetc(f);  //...  b=fgetc(f);//可能此时已经feof了！  //... } 而这样写就没有问题： while (1) {  a=fgetc(f);  if (feof(f)) break;  //...  b=fgetc(f);  if (feof(f)) break;  //... } 类似的例子还可以举很多。 do语句也一样！

好的，我再试试。

在每个最后不带\n的printf后面加fflush(stdout); 在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin); 另外请检查scanf的返回值。 [size=24px][code=c]//请今后要用 char c; scanf("%c",&c); //时，都改为 char s[2]; char c; scanf("%1s",s); c=s[0]; //自动跳过一个或多个空格或Tab字符或回车换行，读取下一个字符。[/code][/size]

4老师牛逼。

去查了一下一下fflush和rewind的用法，然后加上去好像还是没法控制换行。


Question: 最后一位数据后面的逗号怎么消除

1、楼主你的代码不输出逗号啊？ 2、如果要以眼睛为标准，可以最后printf("\b\n"); 3、转换一下思路，你以为是每个数后面带逗号，能不能想象第一个数专门输出为啥也不带，然后循环输出每个数前面带逗号呢？

正解。

#include <stdio.h> int main() {     int n,i;     scanf("%d", &n);     int a[n];     for(i=0;i<n;i++) {         scanf("%d",&a[i]);     }     for(i=0;i<n;i++) {         if( i % 2 != 0) {              printf("%d",a[i]);             if (i != n-1 && i != n-2)                  printf(",");         }     }     printf("\n");     return 0; }


Question: 堆区内存释放的疑问!

可以，注意在主函数异常处理时，该释放的时候也要释放。

可以，只要在一个模块里面就行。 不能跨DLL，释放。 跨函数释放是没有问题的。

参考【算法分享】基于WinSocket的TCP分包组包传输算法_yiyefangzhou24的专栏-CSDN博客

这和是否主函数无关，如果是dll内部函数malloc的内存，只能在dll内部free，如果都在同一个空间，你说的可以。 malloc原则上谁申请谁释放原则，实在不行可以使用c++的string或者内存池

可以


Question: 怎么让之前输入的内容不影响到后面的输入

fflush(stdin) 清空输入缓冲区。


Question: char *name[] = { "Follow me", "BASIC", "Great Wall" };

char *name[] = { "Follow me", "BASIC", "Great Wall" }; 要看编译器怎么处理，这样的字符指针数组一般是，存放3个整形指针，每个指针指向存放字符串的地址，字符串可能不连续在一起，一般可能是连续在一起（每个字符串后至少会有一个'\0'，也可能编译器多加‘\0'),所以地址差值不一定等于长度加一个0的位置

用我惯用的方式表达，就是张三的鼻子到肚脐的距离是有意义的，但是张三的鼻子到李四的耳朵的距离在我们讨论的范畴下是没有意义的。

四老师的解释是站在编译器开发者的角度，解释了一下编译器对静态地址的分配。 而站在程序猿的立场，你需要知道，那三个用于初始化指针数组的字符串，互相之间是没有法定关系的。 我的意思是，那三个字符串并不属于同一个数组什么的，是你把它们的地址组织成了一个数组，而已。 不是同一数组的元素地址之间求差无意义。 所以你那个差值，固然描述了你的机器上你的系统上这一时刻的事实，但它（差值）是个C范畴下的无意义的量。

懂意思了，谢谢～

刚在vs2019上测试了一下, 指针数组的各字符串元素并不一定要连续存储, 元素间的空白存储单元也是随机的.

我的理解，对齐到4的倍数。

看了你的，发现明白了什么意思了。但是字符存储的时候一个字符不是占用1个字节吗？

将地址对齐到4的倍数是为了让CPU读的时候不因为地址不是4的倍数分两次读或抛出异常。

//#pragma warning(disable:4996) //开头加这句或项目、属性、配置属性、C/C++、预处理器、预处理器定义中添加“_CRT_SECURE_NO_WARNINGS” #include<stdio.h> #include<string.h> void HexDump(char *buf,int len,int addr) {     int i,j,k;     char binstr[80];      for (i=0;i<len;i++) {         if (0==(i%16)) {             sprintf(binstr,"%08x -",i+addr);             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         } else if (15==(i%16)) {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);             sprintf(binstr,"%s  ",binstr);             for (j=i-15;j<=i;j++) {                 sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');             }             printf("%s\n",binstr);         } else {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         }     }     if (0!=(i%16)) {         k=16-(i%16);         for (j=0;j<k;j++) {             sprintf(binstr,"%s   ",binstr);         }         sprintf(binstr,"%s  ",binstr);         k=16-k;         for (j=i-k;j<i;j++) {             sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');         }         printf("%s\n",binstr);     } } int main(void) {     char *name[] = { "Follow me", "BASIC", "Great Wall" };     printf("sizeof(name[0]):%d\n", sizeof(name[0]));     for (int i = 0; i < 3; i++)     {         printf("name[%d]:0x%p strlen(name[%d]):%d\n",i,name[i],i,strlen(name[i]));     }     HexDump((char *)(name[2]),48,(int)(name[0]));     return 0; } //sizeof(name[0]):4 //name[0]:0x00403074 strlen(name[0]):9 //name[1]:0x0040306C strlen(name[1]):5 //name[2]:0x00403060 strlen(name[2]):10 //00403074 - 47 72 65 61 74 20 57 61 6c 6c 00 00 42 41 53 49  Great.Wall..BASI //00403084 - 43 00 00 00 46 6f 6c 6c 6f 77 20 6d 65 00 00 00  C...Follow.me... //00403094 - 73 69 7a 65 6f 66 28 6e 61 6d 65 5b 30 5d 29 3a  sizeof(name[0]):  VC6 Release

#pragma warning(disable:4996) //开头加这句或项目、属性、配置属性、C/C++、预处理器、预处理器定义中添加“_CRT_SECURE_NO_WARNINGS” #include<stdio.h> #include<string.h> void HexDump(char *buf,int len,int addr) {     int i,j,k;     char binstr[80];      for (i=0;i<len;i++) {         if (0==(i%16)) {             sprintf(binstr,"%08x -",i+addr);             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         } else if (15==(i%16)) {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);             sprintf(binstr,"%s  ",binstr);             for (j=i-15;j<=i;j++) {                 sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');             }             printf("%s\n",binstr);         } else {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         }     }     if (0!=(i%16)) {         k=16-(i%16);         for (j=0;j<k;j++) {             sprintf(binstr,"%s   ",binstr);         }         sprintf(binstr,"%s  ",binstr);         k=16-k;         for (j=i-k;j<i;j++) {             sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');         }         printf("%s\n",binstr);     } } int main(void) {     char *name[] = { "Follow me", "BASIC", "Great Wall" };     printf("sizeof(name[0]):%d\n", sizeof(name[0]));     for (int i = 0; i < 3; i++)     {         printf("name[%d]:0x%p strlen(name[%d]):%d\n",i,name[i],i,strlen(name[i]));     }     HexDump((char *)(name[0]),48,(int)(name[0]));     return 0; } //sizeof(name[0]):4 //name[0]:0x003E2134 strlen(name[0]):9 //name[1]:0x003E2140 strlen(name[1]):5 //name[2]:0x003E2148 strlen(name[2]):10 //003e2134 - 46 6f 6c 6c 6f 77 20 6d 65 00 00 00 42 41 53 49  Follow.me...BASI //003e2144 - 43 00 00 00 47 72 65 61 74 20 57 61 6c 6c 00 00  C...Great.Wall.. //003e2154 - 73 69 7a 65 6f 66 28 6e 61 6d 65 5b 30 5d 29 3a  sizeof(name[0]):   VS2015 release


Question: 各位大神，下面这个C代码，转成Java代码该怎么写啊

基本运算java和C是一样的，把数据结构和函数转换过去就行了，例如char *变成String，memset和memcpy本质上是赋值操作


Question: 大学c语言考纲，运用c语言统计字符数组(“字符串”)中某个单词出现的次数

供参考：  #include<stdio.h>  int main() {     int i=0;     char str[512],substr[32],*s=str,*p,*q;     gets(str);     getchar();     gets(substr);     while(*s){             p=s;             q=substr;             while(*q){                    if(*q==*p)                       {q++;p++;}                    else                       break;                    if(*q=='\0')i++;           }           s++;     }     printf("%d\n",i);          return 0; }


Question: C语言编写FFT程序

fftw 凑字凑字。。。。

我做过c的FFT库，有现成代码。


Question: 为什么我按行读取txt是这样的呢？

仅供参考：  //NAME: essaie bla bla //DIMENSION: 8 //DATA //1  14  15 //2  11  10 //3  6   4 //4  7   13 //5  9   21 //6  19  3 //7  1   5 //8  8   8 //EOF // // 文本文件中可能还含有其他内容，但是需要用到的内容即以上  //比如data.txt: //NAME: essaie bla bla //其它内容 //DIMENSION: 8 //其它内容 //DATA //其它内容 //1  14  15 //其它内容 //2  11  10 //其它内容 //3  6   4 //其它内容 //4  7   13 //其它内容 //5  9   21 //其它内容 //6  19  3 //其它内容 //7  1   5 //其它内容 //8  8   8 //其它内容 //EOF  // 目标是要获取NAME后字串，DIMENSION后数值，以及DATA以下的数值 // 其中NAME就是随便个字句，DIMENSION是城市数量，DATA以下是城市编号，X坐标，Y坐标 // 所有的这些将赋值给一个事先定义好的结构 #include <stdio.h> #include <string.h> #define MAXCPL   80   //每行最大字符数 #define MAXCITY  100  //每组数据中DATA最多项数，DIMENSION的最大值 #define MAXNAMEL 32   //NAME最大长度 struct S {     char NAME[MAXNAMEL+1];     int  DIMENSION;     struct D {         int NO;         int X;         int Y;     } DATA[MAXCITY]; } s; FILE *f; int st,n,i; char ln[MAXCPL]; int main() {     f=fopen("data.txt","r");     if (NULL==f) {         printf("Can not open file data.txt!\n");         return 1;     }     st=0;     n=0;     while (1) {         if (NULL==fgets(ln,MAXCPL,f)) break;         if (st==0) {             if (1==sscanf(ln,"NAME: %31[^\n]",s.NAME)) st=1;         } else if (st==1) {             if (1==sscanf(ln,"DIMENSION: %d",&s.DIMENSION)) st=2;         } else if (st==2) {             if (0==strcmp(ln,"DATA\n")) st=3;         } else if (st==3) {             if (3==sscanf(ln,"%d%d%d",&s.DATA[n].NO,&s.DATA[n].X,&s.DATA[n].Y)) {                 n++;                 if (n>=MAXCITY || n>=s.DIMENSION) break;             }         }     }     fclose(f);     printf("s.NAME=[%s]\n",s.NAME);     printf("s.DIMENSION=%d\n",s.DIMENSION);     for (i=0;i<n;i++) {         printf("s.DATA[%d].NO,X,Y=%d,%d,%d\n",i,s.DATA[i].NO,s.DATA[i].X,s.DATA[i].Y);     }     return 0; } //s.NAME=[essaie bla bla] //s.DIMENSION=8 //s.DATA[0].NO,X,Y=1,14,15 //s.DATA[1].NO,X,Y=2,11,10 //s.DATA[2].NO,X,Y=3,6,4 //s.DATA[3].NO,X,Y=4,7,13 //s.DATA[4].NO,X,Y=5,9,21 //s.DATA[5].NO,X,Y=6,19,3 //s.DATA[6].NO,X,Y=7,1,5 //s.DATA[7].NO,X,Y=8,8,8

就是还会多一行

那句格式读取文件改这样试试：fscanf(fp,"%s %s %d %f %c %s %s",L.elem[i].id,L.elem[i].name,&L.elem[i].inventory,&L.elem[i].price....)

可以哎！

多一行这样改：while(1){},这里循环里改成1，文件读取那句改成：if（fscanf(fp,"%s %s %d %f %c %s %s",L.elem[i].id,L.elem[i].name,&L.elem[i].inventory,&L.elem[i].price....)!=7) break;

OK啦，谢谢！


Question: 萌新求带啊啊，为什么初始化的值会莫名其妙被改了。我定义的direction[0].incX=1,direction[0].incY=0;为什么被调用的时候都变为零了；

至少得是调用了 startdirtion()之后。 如果还发生值莫名其妙被改变，请参考下面：  #include <time.h> #include <stdlib.h> #include <windows.h> int main() {     int a,b[11];//本来是b[10]，为判断哪句越界，故意声明为b[11]      srand((unsigned int)time(NULL));//按两次F11，等黄色右箭头指向本行时，调试、新建断点、新建数据断点，地址：&b[10]，字节计数：4，确定。     while (1) {//按F5，会停在下面某句，此时a的值为10，b[10]已经被修改为对应0..4之一。         b[(a=rand()%11)]=0;         Sleep(100);         b[(a=rand()%11)]=1;         Sleep(100);         b[(a=rand()%11)]=2;         Sleep(100);         b[(a=rand()%11)]=3;         Sleep(100);         b[(a=rand()%11)]=4;         Sleep(100);     }     return 0; }

全局变量被显式赋值之前就应该是0来着。 您回避了这个关键点，就是上述图片是调试到哪个位置时的状态。

我是在定义findpath里的  while (di < 4)         {             system("pause");             //system("cls");             line = x + direction[di].incX;             col = y + direction[di].incY;  //加的断点

函数findpath里面的direction是来自形参的局部变量，并在函数调用时得到了一个错误的实参。 为什么不直接使用全局变量呢？

啊 确实，我脑子可能瓦特了。而且我发现了更多错误，而且在findpath函数里调用的print函数打印不出来画面。问题越来越多了2333

这是所有的代码。求教。

#include<stdio.h> #include<malloc.h> #include<stdlib.h> #include<Windows.h> #define M 20//迷宫长度 #define N 20//迷宫宽度 int maze[M][N] = {0}; typedef struct//角色可行驶方向 {     int incX;     int incY; }Direction; Direction direction[4]; typedef struct Box//角色当前位置与当前方向 {     int dirction_x, dirction_y;     int dir;     struct Box* next; }BOX,*PBOX; typedef struct Stack {     PBOX pTop;     PBOX pBttom;                 }STACK,*PSTACK; void init(PSTACK S)//创建头节点 {     S->pTop = (PBOX)malloc(sizeof(BOX));     if (S->pTop == NULL)     {         printf("内存分配失败");         exit(-1);     }     S->pBttom = S->pTop;     S->pTop->next = NULL; } void Push(PSTACK S,PBOX b) {     PBOX bNew = (PBOX)malloc(sizeof(BOX));     if (bNew)     {         bNew->dirction_x = b->dirction_x;         bNew->dirction_y = b->dirction_y;         bNew->dir = b->dir;         bNew->next = S->pTop;         S->pTop = bNew;     } } void Pop(PSTACK S,PBOX b) {     if (S->pTop == S->pBttom)return;     b->dirction_x = S->pTop->dirction_x;     b->dirction_y = S->pTop->dirction_y;     b->dir = S->pTop->dir;     PBOX L = S->pTop;     S->pTop = L->next;     free(L);     L = NULL; } void startdirtion()//填充行走方向 {     direction[0].incX = 1; direction[0].incY = 0;     direction[1].incX = 0; direction[1].incY = 1;     direction[2].incX = -1; direction[2].incY = 0;     direction[3].incX = 0; direction[3].incY = -1; } void print(int maze[M][N])//输出画面 {     for (int j = 0; j < N; j++)     {         for (int i = 0; i < M; i++)         {             if (maze[i][j] == 9)printf("@");             if (maze[i][j] == 1)printf("#");             if (maze[i][j] == 0)printf(" ");         }         printf("\n");     } } bool findpath(int maze[M][N],Direction direction[],PSTACK S)//判断是否有路可走 {     BOX temp;     int x, y, di;     int line, col;     maze[1][1] = -1;     temp = { 1,1,-1 };     Push(S,&temp);     while (S->pTop != S->pBttom)     {         Pop(S,&temp);         x = temp.dirction_x; y = temp.dirction_y; di = temp.dir + 1;         while (di < 4)         {             system("pause");             //system("cls");             line = x + direction[di].incX;             col = y + direction[di].incY;             if (maze[line][col] == 0)             {                 temp = { x,y,di };                 Push(S, &temp);                 maze[x][y] = 9;                 print(maze);                 maze[x][y] = 0;                 x = line; y = col; maze[line][col] = -1;                 if (x == M && y == N)return true;                 else di = 0;             }             else di++;         }     }     return false; } void startmaze()//初始化迷宫 {     for (int i = 0; i < M; i++)//给迷宫上下两行的墙赋值     {         maze[i][0] = 1;         maze[i][N-1] = 1;     }     for (int i = 0; i < N; i++)//给左右赋值     {         maze[0][i] = 1;         maze[M-1][i] = 1;     } } void startdate()//数据集中初始化 {     startdirtion();     startmaze(); } int main() {     STACK S;     init(&S);     startdate();     //print(maze);     findpath(maze, &direction[4], &S);          char text = getchar(); }


Question: 在keil芯片仿真遇到单步调试与实际不符的情况

最终确认是因为没做好措施，因为静电原因导致的电路板某处短路，造成了一系列不正常的状况

经检查可能是某个引脚初始化的时候漏电了，，，，，，注释掉相关部分运行就没有问题了，但是这个初始化的部分和显示完全不沾边，，，，，等待后续检测

速度太快？


Question: Vc++6.0清屏！！小白求带：（

system("cls");不会退出程序吧，是你程序自己结束了？

system("cls");还有这功能?

请证明您的描述确有其事，然后再继续哭。


Question: 为什么用float配合%f会溢出用double配合%lf不会？？？

对于double的变量,scanf要用%lf，printf也建议用%lf

图文不一致，南辕北辙了。

1.C语言中printf输出float和double都可以用%f,而double型数据还可以用%lf。 2.scanf当中若是对双精度的变量赋值是必须是%后跟lf,而printf当中可以用%f也可以用%lf没有限制


Question: 一个关于结构指针的疑问

注释的三行大约是p和t一起抄了第一名同学的作业，然后p撕掉了自己的作业本。 然而， 下面四行是说第一名同学小名叫做p，t童鞋抄了他的作业，然后p撕掉了自己的作业本。

我的问题是为什么运行注释掉的三行后hashtab[0]!=NULL, 而运行它下面的四行后, hashtab[0]==NULL?

我说的正是这个事儿啊。 上面的第一名同学的作业还在，自然就不是NULL了； 下面的第一名同学作业被撕了，自然就NULL了。

不打比方的说法是，四行版里面*p就是hashtab[0]本身，你修改了人家的值。


Question: vscode'cmd' 不是内部或外部命令，也不是可运行的程序或批处理文件。如何解决

“终端”就是控制台 cmd.exe ，你所谓的“黑窗口”。 你或许需要呼吸点新鲜空气了。


Question: 求助帖

新改的论坛乱码了？？#include <stdio.h> 好像行了，显然不行，那是你的编译器放了你一马。多换几个编译器，早晚出错。 1. 用动态分配，楼上提到的malloc。 2. 定义一个足够大的数组。int Num[100]，假设输入的n小于100。

好的，多谢，鄙人纯新手，感谢指教

#include <stdio.h> int main()  {     int n,i=0;     scanf("%d",&n);     int Num[n];     while (i<=n)     {         if(i>=0&i<n)         {             scanf("%d",&Num[i]);             i=i+1;         }              else         break;     } } 修改了一下，好像可以？

int Num[n];这个C语言不清楚应该给这个数组Num定义多大，因为这个n是需要我们输入才会知道。所以，不建议这么写（C++可以）

好的好的，谢谢

数组需要是一个定值（确定的）；如果要这么做也是可以，使用malloc吧；  #include <stdio.h> #include <stdlib.h> //Windows下用<malloc.h> int main()  {     int n,i=0;     scanf("%d",&n);     int *N = (int *)malloc(sizeof(int) * n);//[n];     while (1)     {         for(i=0;i<n;i++)         scanf("%d",&N[i]);     }     free(N);     return 0; } 供参考～

int *N = (int *)malloc(sizeof(int) * n);  这一语句的意思是不是定义一个个数为n的整型数组啊？ 另 #include <stdio.h> int main()  {     int n,i=0;     scanf("%d",&n);     int Num[n];     while (i<=n)     {         if(i>=0&i<n)         {             scanf("%d",&Num[i]);             i=i+1;         }         else         break;     } } 这个好像可以实现读入一个个数已知的数组？

数组n不能是变量

好的，感谢

#include <stdio.h> int main()  {     int n,i=0;     scanf("%d",&n);     int Num[n];     while (i<=n)     {         if(i>=0&i<n)         {         	scanf("%d",&Num[i]);         	i=i+1; 		} 	         else         break;     } } 这样好像就行了，不知道有没有问题？

int N[n] 在编译的时候需要在栈上预分配n个int类型的空间, 但是你的n是一个变量, 一个不确定的变量. 这是错误的根本原因. 对照规则有2中修复方式: 1. n 定义为一个常量, 这个时候可以预分配成功. 2. 数组N 在堆上动态分配, 使用new操作符.

好的，感谢


Question: C语言中如何处理10万组级别的数据

不要说什么栈空间。 楼主的代码别的不看，就那一个数组的大小，数一数，那是百万行百万列，4TB数量级。 我根本就不信楼主的机器有那么大的内存啊，包括虚拟的。你们信么？ ------------------------------------------------------------ 对数据规模我们应保有基本的敬畏。

您好，多谢您的提醒， 1. 我现有的手上数据是10W行，2列，我如果用malloc分配内存空间的话，就需要2x10万x4字节=0.8Mb的空间，对吗?  2. 如果真的需要处理百万行与百万列的话，如果还是用malloc分配，是否只能在物理上扩大内存来解决？有其他途径吗？

0.8MB直接写数组就行。 但是真的那么大就只能一块一块处理了，先研究算法。 那么大的数据全部装进内存既不现实，也没必要。

仅供参考：  #pragma warning(disable:4996 4244) #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define MAXW 1024 char A[MAXW],B[MAXW]; FILE *fb; #define CUTOFF 8            /* testing shows that this is good value */  /* Note: the theoretical number of stack entries required is    no more than 1 + log2(num).  But we switch to insertion    sort for CUTOFF elements or less, so we really only need    1 + log2(num) - log2(CUTOFF) stack entries.  For a CUTOFF    of 8, that means we need no more than 62 stack entries for    64-bit platforms. */ //#define STKSIZ (8*sizeof(void*) - 2) #define STKSIZ   (8*8             - 2)  /*** *swap(a, b, w) - swap two elements * *Purpose: *       swaps the two file elements of size width * *Entry: *       long long int a, b = pointer to two elements to swap *       long long int width = width in bytes of each file element * *Exit: *       returns void * *Exceptions: * *******************************************************************************/  static void swap(     long long int a,     long long int b,     long long int w     ) {     if ( a != b ) {         _fseeki64(fb,a,SEEK_SET);         fread(A,w,1,fb);         _fseeki64(fb,b,SEEK_SET);         fread(B,w,1,fb);         _fseeki64(fb,a,SEEK_SET);         fwrite(B,w,1,fb);         _fseeki64(fb,b,SEEK_SET);         fwrite(A,w,1,fb);     } }  /*** *shortsort(hi, lo, width, comp) - insertion sort for sorting short file * *Purpose: *       sorts the file of elements between lo and hi (inclusive) *       side effects:  sorts in place *       assumes that lo < hi * *Entry: *       long long int lo = pointer to low element to sort *       long long int hi = pointer to high element to sort *       long long int width = width in bytes of each file element *       int (*comp)() = pointer to function returning analog of strcmp for *               strings, but supplied by user for comparing the file elements. *               it accepts 2 pointers to elements, together with a pointer to a context *               (if present). Returns neg if p1<p2, 0 if p1==p2, pos if p1>p2. * *Exit: *       returns void * *Exceptions: * *******************************************************************************/  static void shortsort(     long long int lo,     long long int hi,     long long int width,     int (*comp)(long long int, long long int,long long int)     ) {     long long int p, maxp;      /* Note: in assertions below, i and j are alway inside original bound of        file to sort. */      while (hi > lo) {         /* A[i] <= A[j] for i <= j, j > hi */         maxp = lo;         for (p = lo+width; p <= hi; p += width) {             /* A[i] <= A[maxp] for lo <= i < p */             if (comp(p, maxp, width) > 0) {                 maxp = p;             }             /* A[i] <= A[maxp] for lo <= i <= p */         }          /* A[i] <= A[maxp] for lo <= i <= hi */          swap(maxp, hi, width);          /* A[i] <= A[hi] for i <= hi, so A[i] <= A[j] for i <= j, j >= hi */          hi -= width;          /* A[i] <= A[j] for i <= j, j > hi, loop top condition established */     }     /* A[i] <= A[j] for i <= j, j > lo, which implies A[i] <= A[j] for i < j,        so file is sorted */ }  /*** *fqsort(base, num, width, comp) - quicksort function for sorting file * *Purpose: *   quicksort the file of elements *   side effects:  sorts in place *   maximum file size is number of elements times size of elements, *   but is limited by the file size of the OS and disk free space. * *Entry: *   long long int base = pointer to base of file *   long long int num  = number of elements in the file *   long long int width = width in bytes of each file element *   int (*comp)() = pointer to function returning analog of strcmp for *           strings, but supplied by user for comparing the file elements. *           it accepts 2 pointers to elements. *           Returns neg if p1<p2, 0 if p1==p2, pos if p1>p2. * *Exit: *   returns void * *Exceptions: *   Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/  void fqsort(     long long int base,     long long int num,     long long int width,     int (*comp)(long long int, long long int, long long int)     ) {     long long int lo, hi;              /* ends of sub-file currently sorting */     long long int mid;                  /* points to middle of subarray */     long long int loguy, higuy;        /* traveling pointers for partition step */     long long int size;                /* size of the sub-file */     long long int lostk[STKSIZ], histk[STKSIZ];     int stkptr;                 /* stack for saving sub-file to be processed */      /* validation section */     assert(base>=0 && num > 0);     assert(width > 0);     assert(comp != NULL);      if (num < 2)         return;                 /* nothing to do */      stkptr = 0;                 /* initialize stack */      lo = base;     hi = base + width * (num-1);        /* initialize limits */      /* this entry point is for pseudo-recursion calling: setting        lo and hi and jumping to here is like recursion, but stkptr is        preserved, locals aren't, so we preserve stuff on the stack */ recurse:      size = (hi - lo) / width + 1;        /* number of el's to sort */      /* below a certain size, it is faster to use a O(n^2) sorting method */     if (size <= CUTOFF) {         shortsort(lo, hi, width, comp);     }     else {         /* First we pick a partitioning element.  The efficiency of the            algorithm demands that we find one that is approximately the median            of the values, but also that we select one fast.  We choose the            median of the first, middle, and last elements, to avoid bad            performance in the face of already sorted data, or data that is made            up of multiple sorted runs appended together.  Testing shows that a            median-of-three algorithm provides better performance than simply            picking the middle element for the latter case. */          mid = lo + (size / 2) * width;      /* find middle element */          /* Sort the first, middle, last elements into order */         if (comp(lo, mid, width) > 0) {             swap(lo, mid, width);         }         if (comp(lo, hi, width) > 0) {             swap(lo, hi, width);         }         if (comp(mid, hi, width) > 0) {             swap(mid, hi, width);         }          /* We now wish to partition the file into three pieces, one consisting            of elements <= partition element, one of elements equal to the            partition element, and one of elements > than it.  This is done            below; comments indicate conditions established at every step. */          loguy = lo;         higuy = hi;          /* Note that higuy decreases and loguy increases on every iteration,            so loop must terminate. */         for (;;) {             /* lo <= loguy < hi, lo < higuy <= hi,                A[i] <= A[mid] for lo <= i <= loguy,                A[i] > A[mid] for higuy <= i < hi,                A[hi] >= A[mid] */              /* The doubled loop is to avoid calling comp(mid,mid,width), since some                existing comparison funcs don't work when passed the same                value for both pointers. */              if (mid > loguy) {                 do  {                     loguy += width;                 } while (loguy < mid && comp(loguy, mid, width) <= 0);             }             if (mid <= loguy) {                 do  {                     loguy += width;                 } while (loguy <= hi && comp(loguy, mid, width) <= 0);             }              /* lo < loguy <= hi+1, A[i] <= A[mid] for lo <= i < loguy,                either loguy > hi or A[loguy] > A[mid] */              do  {                 higuy -= width;             } while (higuy > mid && comp(higuy, mid, width) > 0);              /* lo <= higuy < hi, A[i] > A[mid] for higuy < i < hi,                either higuy == lo or A[higuy] <= A[mid] */              if (higuy < loguy)                 break;              /* if loguy > hi or higuy == lo, then we would have exited, so                A[loguy] > A[mid], A[higuy] <= A[mid],                loguy <= hi, higuy > lo */              swap(loguy, higuy, width);              /* If the partition element was moved, follow it.  Only need                to check for mid == higuy, since before the swap,                A[loguy] > A[mid] implies loguy != mid. */              if (mid == higuy)                 mid = loguy;              /* A[loguy] <= A[mid], A[higuy] > A[mid]; so condition at top                of loop is re-established */         }          /*     A[i] <= A[mid] for lo <= i < loguy,                A[i] > A[mid] for higuy < i < hi,                A[hi] >= A[mid]                higuy < loguy            implying:                higuy == loguy-1                or higuy == hi - 1, loguy == hi + 1, A[hi] == A[mid] */          /* Find adjacent elements equal to the partition element.  The            doubled loop is to avoid calling comp(mid,mid,width), since some            existing comparison funcs don't work when passed the same value            for both pointers. */          higuy += width;         if (mid < higuy) {             do  {                 higuy -= width;             } while (higuy > mid && comp(higuy, mid, width) == 0);         }         if (mid >= higuy) {             do  {                 higuy -= width;             } while (higuy > lo && comp(higuy, mid, width) == 0);         }          /* OK, now we have the following:               higuy < loguy               lo <= higuy <= hi               A[i]  <= A[mid] for lo <= i <= higuy               A[i]  == A[mid] for higuy < i < loguy               A[i]  >  A[mid] for loguy <= i < hi               A[hi] >= A[mid] */          /* We've finished the partition, now we want to sort the subarrays            [lo, higuy] and [loguy, hi].            We do the smaller one first to minimize stack usage.            We only sort arrays of length 2 or more.*/          if ( higuy - lo >= hi - loguy ) {             if (lo < higuy) {                 lostk[stkptr] = lo;                 histk[stkptr] = higuy;                 ++stkptr;             }                           /* save big recursion for later */              if (loguy < hi) {                 lo = loguy;                 goto recurse;           /* do small recursion */             }         }         else {             if (loguy < hi) {                 lostk[stkptr] = loguy;                 histk[stkptr] = hi;                 ++stkptr;               /* save big recursion for later */             }              if (lo < higuy) {                 hi = higuy;                 goto recurse;           /* do small recursion */             }         }     }      /* We have sorted the file, except for any pending sorts on the stack.        Check if there are any, and do them. */      --stkptr;     if (stkptr >= 0) {         lo = lostk[stkptr];         hi = histk[stkptr];         goto recurse;           /* pop subarray from stack */     }     else         return;                 /* all subarrays done */ }   /*** *long long int fbsearch() - do a binary search on an file * *Purpose: *   Does a binary search of a sorted file for a key. * *Entry: *   const void *key    - key to search for *   const long long int base   - base of sorted file to search *   unsigned int num   - number of elements in file *   unsigned int width - number of bytes per element *   int (*compare)()   - pointer to function that compares key and file *           elements, returning neg when #1 < #2, pos when #1 > #2, and *           0 when they are equal. Function is passed pointers to key *           and pointer to file elements. * *Exit: *   if key is found: *           returns pointer to occurrence of key in file *   if key is not found: *           returns -1 * *Exceptions: *   Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/  long long int fbsearch(     const void *key,     long long int base,     long long int num,     long long int width,     int (*compare)(const void *, long long int, long long int)     ) {     long long int lo = (long long int)base;     long long int hi = (long long int)base + (num - 1) * width;     long long int mid;     long long int half;     int result;      /* validation section */     assert(base>=0 && num > 0);     assert(width > 0);     assert(compare != NULL);          /*         We allow a NULL key here because it breaks some older code and because we do not dereference         this ourselves so we can't be sure that it's a problem for the comparison function         */      while (lo <= hi)     {         if ((half = num / 2) != 0)         {             mid = lo + (num & 1 ? half : (half - 1)) * width;             if (!(result = compare(key, mid, width)))                 return(mid);             else if (result < 0)             {                 hi = mid - width;                 num = num & 1 ? half : half-1;             }             else             {                 lo = mid + width;                 num = half;             }         }         else if (num)             return (compare(key, lo, width) ? -1 : lo);         else             break;     }      return -1; } int cmp(long long int a, long long int b, long long int w) {     _fseeki64(fb,a,SEEK_SET);     fread(A,w,1,fb);     _fseeki64(fb,b,SEEK_SET);     fread(B,w,1,fb);     return strncmp(A,B,w); } int cmps(const void *k, long long int b, long long int w) {     _fseeki64(fb,b,SEEK_SET);     fread(B,w,1,fb);     return strncmp((const char *)k,B,w); } void test(int n,int w,void *k1,void *k2) {     int i,v;     long long int r;      assert(w<MAXW);     fb=fopen("test.bin","wb");     if (NULL==fb) {         printf("Can not create file test.bin!\n");         return;     }     for (i=0;i<n;i++) {         v=10+rand()%90;         printf("%02d ",v);         fprintf(fb,"%02d\r\n",v);     }     printf("\n");     fclose(fb);      fb=fopen("test.bin","rb+");     if (NULL==fb) {         printf("Can not open file test.bin!\n");         return;     }     fqsort(0,n,w,cmp);     r=fbsearch(k1,0,n,w,cmps);     printf("%s r1:%lld\n",k1,r);     r=fbsearch(k2,0,n,w,cmps);     printf("%s r2:%lld\n",k2,r);     fclose(fb);     system("type test.bin"); } int main() {     srand(0);      test(  8,4,"75\r\n","12\r\n");     test(100,4,"94\r\n","95\r\n");      return 0; }

栈没那么大，前面加上static试试，如果不行，建议把数组定义为合适的大小，数组定义这么大，是可以存放10w × 10w个float数据的，这个是你需要的大小吗？

即使加上static不合适，那么把数组定义成合适大小，也需要加上static

使用文件游标,一次读一部分数据(固定行数,比如100行)到缓冲区处理.

把数组a做成全局变量，或者用动态内存分配。


Question: C语言-求助

typedef struct Student {     double num;     //struct Studnet *next;     struct Student *next; }stu; 单词拼写错误，比较低级的错误～

#include <stdio.h> #include <stdlib.h> typedef struct Student { 	double num; 	struct Student* next; } *stu;  int main() { 	stu student(int),  head; 	void sum(stu  head,double *,double *,double *); 	int n; 	double sums,max,min;  	scanf_s("%d", &n); 	head = student(n); 	sums = max = 0.0; 	sum(head,&sums,&max,&min); 	printf("average = %.1f\nmax = %.1f\nmin = %.1f", sums / n, max, min); 	return 0; } stu student(int n) { 	stu head,  p;  	head = NULL; 	while (n > 0) { 		p = (stu)(malloc(sizeof(struct Student))); 		if (p == NULL) 			return NULL; 		scanf_s("%lf", &p->num); 		p->next = head; 		head = p; 		n--; 	} 	return head; } void sum(stu head,double* sums,double *max,double *min) { 	stu p; 	p = head; 	*min = p->num; 	while (p != NULL) { 		*sums +=  p->num; 		if (p->num > *max) { 			*max = p->num; 		} else if (p->num < *min) { 			*min = p->num; 		} 		p = p->next; 	}  }

typedef struct Student { 	double num; 	struct Studnet *next; }stu;  结构体重的 struct Studnet *next；中的Studnet拼写错误，应该是struct Student *next


Question: 请问这个语句怎么改写，提示 将 NULL 转换到非指针类型‘char’

谢谢了

全局变量（或静态变量）不手动初始化，系统会默认给初始化的。即static CMDS commands;这样定义，系统会给初始化的，默认是0和NULL，字符串是'\0'


Question: 请问 关于读 TXT文件到 结构体 关于typedef void (*handler)(void) 这样的如何赋值

谢谢了

既然是格式化的数据内容，可以用fscanf读取； on / off这些可以直接赋值，函数指针就不能用字符串直接赋值了。可以比较字符串比如strcmp(str, "Cmd_on");然后xxx.cmd_operate = Cmd_on;    cmd_operate


Question: 请教诸位大佬，关于一定范围内隔数随机数的问题

提供一种思路   #include <stdio.h> #include <stdlib.h> #include <time.h>  /*生成随机数 6，10，14，18，22 */  int GenerateSpecifyRandomNumber(int baseNumber) {     return baseNumber + rand() % 5 * 4; }  int main() {     srand((unsigned int)time(NULL));     int randomNumber;     for (int i = 0; i < 10; i++)     {         randomNumber = GenerateSpecifyRandomNumber(6);         printf("%d\n", randomNumber);     }     return 0; }

好的 我再仔细看看  万分感谢

将这四个数放到数组里，然后随机产生两个数（数组下表），只要随机产生的这两个数（5个数，对5取余）相差1，那么这两个数作为下表对应的数就是相差4的～

原来是这样 因为还没有学到数组 所以没想到这里   感谢大佬


Question: Mips 怎么读取 cache 命中率

查对应的芯片手册，找到对应的cache章节的寄存器，看有没有你需要的寄存器。 顺便说一句，性能的提升一般来通过算法来解决，代码级的优化把常用的结构体尽量cache line对齐。


Question: 【求助】有无大佬知道如何用C语言去编写CGI通信录

长大？

是，呜呜呜

CGI是一个接口，可以网上搜一下CGI源码～


printf("b=%f",&b); 去掉b前面的&就好了。

printf里面的%和变量的一一对应关系 scanf里面的%和变量以及变量前加不加&的一一对应关系 是C代码中非常容易出错的地方，而且通常编译还不出错。 所以在编译源代码之前值得专门仔细检查一遍甚至多遍。

//printf("b=%f",&b);     printf("b=%f",b); &b是地址，类型是unsigned long类型，用%f输出unsigned long，得到是是0.00000正常的，建议看一下浮点型和整型变量在内存里的表示方法，它们是有区别的。

输出变量的值: printf("b=%f",b); 输出存放变量值的地址:printf("%p",&b);


Question: 关于Visual Studio 2015下载后不能使用的问题

安装的时候不能直接选择下一步，要手动选择所需要的功能，默认不安装c++环境的。

显然安装错了工作负荷, 应安装"使用C++的桌面开发"; 可以运行"Visual studio Installer"修改.


Question: 求助帖

这个函数返回值是   int * 指针，这个指针指向  int* ret = malloc(sizeof(int) * 2);   ret[2]数组。

奥奥，感谢

返回整形的指针

好的好的，感谢


Question: C初学者的求助

试试这样：  #include <stdio.h> #include <windows.h> #include <math.h> #include <string.h> int main() { 	int i = 0; 	const char *s = "你好，我的朋友。\n"; 	int size = strlen(s);          printf("%c",s[0]);         printf("%c",s[1]);         printf("\n");  	printf("size = %d", size); 	 }

我大概知道了。char类型1个字节装不下中文，中文应该是多个字节储存的，所以size才会为17。只输出s[0]，屏幕上不会显示中文，但是在后面接上s[1]时，s[0]和s[1]组成了中文符号“你”。 但让我疑惑的时s[0]和s[1]进行了什么运算或者过程，最终才会显示为中文。 我还是什么都不知道。

去了解下汉字的编码方式。


Question: 有人可以帮我分析一下每条语句的作用是什么吗

代码功能归根结底不是别人帮自己看或讲解或注释出来的；而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。 提醒：再牛×的老师也无法代替学生自己领悟和上厕所！ 单步调试和设断点调试（VS IDE中编译连接通过以后，按F10或F11键单步执行，按Shift+F11退出当前函数；在某行按F9设断点后按F5执行停在该断点处。）是程序员必须掌握的技能之一。 VS IDE中，在不明白的符号上点鼠标右键，选转到定义。