一开始写了个代码,输出结果表示莫名奇妙,
<img src="https://img-blog.youkuaiyun.com/20160313133738316?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
#include<stdio.h>
#include<stdlib.h>
#define maxn 20
typedef struct table_type{
int a[maxn];
int length;
} table_type;
table_type *table;
//o123,length=4,1,2,3,4,a[2]jfrom 4 to 2,
table_type *Insert(table_type *table,int x,int i){
int j;
for( j=table->length;j>i-1;j--){
table->a[j]=table->a[j-1];
}
table->a[--j]=x;
table->length++;
}
table_type *Print(table_type *table){
for(int i=0;i<table->length;i++){
printf("%d",table->a[i]);
}
printf("\n");
return table;
}
void Delete(table_type *table,int x){
int i=0;
while(table->a[i]!=x)
i++;
for(int j=i;j<table->length;j++){
table->a[j]=table->a[j+1];
}
table->length--;
}
int main(){
table=(table_type*)malloc(sizeof(struct table_type));
table->length=0;
int i=0,t;
while(scanf("%d",&t)==1&&t!=-1){
table->a[i]=t;
i++;
table->length++;
}
Print(table);
Insert(table,0,2);
Print(table);
}
后来发现,for循环里的j循环结束后的值是j-1而不是j,真是糊涂了
正确代码:
<pre name="code" class="cpp">#include<stdio.h>
#include<stdlib.h>
#define maxn 20
typedef struct table_type{
int a[maxn];
int length;
} table_type;
table_type *table;
table_type *Print(table_type *table){
for(int i=0;i<table->length;i++){
printf("%d",table->a[i]);
}
printf("\n");
return table;
}
table_type *Insert(table_type *table,int x,int i){
int j;
for( j=table->length;j>i-1;j--){
table->a[j]=table->a[j-1];
}
table->a[i-1]=x;
table->length++;
Print(table);
}
void Delete(table_type *table,int x){
int i=0;
while(table->a[i]!=x)
i++;
for(int j=i;j<table->length;j++){
table->a[j]=table->a[j+1];
}
table->length--;
Print(table);
}
int main(){
table=(table_type*)malloc(sizeof(struct table_type));
table->length=0;
int i=0,t,x;
printf("pelase init the table\n");
while(scanf("%d",&t)==1&&t!=-1){
table->a[i]=t;
i++;
table->length++;
}
Print(table);
printf("******************************\n");
printf("|-Please enter a command code!|\n");
printf("|input a new data ,enter 1 |\n");
printf("|delete a data, enter 2 |\n");
printf("|quit the system, enter 0 |\n");
printf("******************************\n");
for(;;){
scanf("%d",&t);
if(t==0) break;
if(t==1){
scanf("%d %d",&x,&i);
Insert(table,x,i);
}
else {
scanf("%d",&x);
Delete(table,x);
}
}
}