Earned from a C language practice platform, only for this sharing...
Share this time:
- Code display
- Code analysis
Code display:
#include<stdio.h>
#include<string.h>
void sort(char *name[],int n);
void print(char *name[],int n);
int main()
{
char *name[5];
char a[31],b[31],c[31],d[31],e[31];
int i,n=5;
name[0]=a;name[1]=b;name[2]=c;name[3]=d;name[4]=e;
printf("Please input 5 strings:");
for(i=0;i<5;i++)
gets(name[i]);
printf("Output:\n");
sort(name,5);
printf("After the strings are sorted the result:\n");
print(name,5);
return 0;
}
void sort(char *name[],int n)
{
int i,j;
char *temp;
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}
void print(char *name[],int n)
{
int i;
for(i=0;i<5;i++)
{
printf("%s\n",name[i]);
}
}
Code analysis:
char *name[5];
char a[31],b[31],c[31],d[31],e[31];
int i,n=5;
name[0]=a;name[1]=b;name[2]=c;name[3]=d;name[4]=e;
This part is actually a two-dimensional character array, considering that I wrote the following code here:
char *name[5][30];
int i,n=5;
The two writing methods are exactly the same when the black box appears for input, if written as char *name[5]; it will be terminated.
Although the second type of writing is exactly the same as the first type of input, it takes into account the formal parameters of the two sub-functions, as follows:
void sort(char *name[],int n);
void print(char *name[],int n);
with
char *name[5][30];
int i,n=5;
The char *name[5][30]; does not match, and the two sub-functions cannot be called after inputting the data.
Therefore, when you press Enter, the program will crash and close the black box directly.
I guess my writing should be that the three-dimensional character array does not match the sub-function
the following:
void sort(char *name[],int n)
{
int i,j;
char *temp;
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}
This part of the code is a simple numeric bubble sort applied to the sorting of a two-dimensional character array.