#include "stdio.h"typedef struct{ char ch[40]; int len;}SString;void StrInsert(SString *s,int pos,SString *t){ int i; if(pos<0||pos>s->len) printf("pos is err\n"); if(s->len+t->len<=40) { for(i=s->len-1;i>=pos;i--) s->ch[i+t->len]= s->ch[i]; for(i=pos;i<t->len+pos;i++) s->ch[i]=t->ch[i-pos]; s->len=s->len+t->len; } else printf("insert is err\n");}void InitStr(SString *s){ int i=0; char k[40]; scanf("%s",k); for(i;k[i]!=0;i++) s->ch[i]=k[i]; s->len=i; }void main(){ void StrInsert(SString *s,int pos,SString *t); void InitStr(SString *s); SString *a,*t; InitStr(a); InitStr(t); StrInsert(a,2,t); printf("%s\n%d",a->ch,a->len);}
for(i=s->len-1;i>=pos;i--) s->ch[i+t->len]= s->ch[i];/*这个地方的怎么加不上去啊。。。
for(i=s->len;i>=pos;i--)
引用第7楼ppdoll于2007-12-02 16:38发表的 :按我的理解最后那个0x0应该是在我为字符数组赋值结束后自动加上去,不知道理解对不对
引用第8楼luwen于2007-12-02 16:43发表的 :不对
InitStr()里给s->ch[i]赋值之前没有先为s分配空间……
#include<stdio.h>#include<string.h>typedef struct { char ch[40]; int len;}SString;void StrInsert(SString *s, int pos, SString *t) { int i; if(pos<0||pos>s->len) { printf("pos is err\n"); return; } if(s->len+t->len>=40) { printf("insert is err\n"); return; } for(i=s->len-1;i>=0;i--) s->ch[i+t->len]=s->ch[i]; for(i=pos;i<t->len+pos;i++) s->ch[i]=t->ch[i-pos]; s->len+=t->len; s->ch[s->len]=0;}void InitStr(SString *s) { scanf("%s", &s->ch); s->len = strlen(s->ch);}void main() { SString a, t; InitStr(&a); InitStr(&t); StrInsert(&a, 2, &t); printf("%s\n%d", a.ch, a.len);}